@extantape/payload-plugin-hats 0.3.1 → 0.4.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
@@ -8,7 +8,7 @@ Linked accounts and role hats for Payload. One person links their accounts and s
8
8
 
9
9
  - **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set. Unlinking is self-serve and immediate.
10
10
  - **Hats.** Wearing a hat narrows the user before `req.user` exists, so every access rule follows it: admin, REST, GraphQL and the Local API with `req`. If narrowing fails, the request is signed out, never given full roles.
11
- - **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 3 hours per account (or per linked set, see below).
11
+ - **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 180 minutes (`stepUp.rememberMinutes`) per account, or per linked set (see below).
12
12
  - **Step up on gain.** Pass `stepUpWhen` to decide for yourself when a switch asks for a code, in place of the `sensitive` flag. It gets the hat worn now (`from`) and the one it would become (`to`), each with the user as it would be worn, so a site can ask only when `to` holds a role or permission that `from` doesn't. Going down asks nothing, going up or sideways asks. Only an exact `false` skips the code. `true`, a throw or any other answer asks, so a broken check never lets a switch through.
13
13
  - **One code for the whole set.** `stepUp.rememberPer: 'set'` remembers a good code for every account in the same linked set, for the same 3 hours, so one two-step covers the person. The default, `'account'`, is unchanged. An account in no set is remembered on its own either way. `stepUp.available` and `stepUp.verify` also get `signedIn` (the account that actually signed in) and `set` (the linked set's id, or `null`), so a site can check against one two-step for the person. `user` stays the account being switched into.
14
14
  - **Revocation.** Unlinking, deleting a row, losing a role or deleting an account ends every session switched into or through it. Switched sessions also re-check their set on every request. An ended session's record is kept, marked revoked, so a session that Payload writes back by accident (two writes to an account's sessions at once) stays signed out. Old records are deleted once their Payload session is gone, at most 50 per switch.
@@ -80,6 +80,35 @@ Colors and sizes come from `--hats-ink`, `--hats-paper`, `--hats-line`, `--hats-
80
80
 
81
81
  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.
82
82
 
83
+ ## Switching from your own route
84
+
85
+ `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.
86
+
87
+ ```ts
88
+ // app/api/enter-admin/route.ts (Next.js). Your own POST route, not the picker.
89
+ import { getPayload, type PayloadRequest } from 'payload'
90
+ import config from '@payload-config'
91
+ import { switchSession } from '@extantape/payload-plugin-hats'
92
+
93
+ export async function POST(request: Request) {
94
+ const payload = await getPayload({ config })
95
+ const { user } = await payload.auth({ headers: request.headers }) // the person's own sign-in cookie
96
+ if (!user) return Response.json({ reason: 'signIn' }, { status: 401 })
97
+ const { account, hat, code } = await request.json() // ids from your own screen; code only when it asked for one
98
+ // The plugin reads method, Origin and Sec-Fetch-Site from this request and refuses a cross-site call.
99
+ const req = { payload, user, headers: request.headers, method: request.method, url: request.url } as unknown as PayloadRequest
100
+ const result = await switchSession(req, { account, hat, code })
101
+ if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status }) // needsCode, wrongCode, blocked, notLinked, locked ...
102
+ return new Response(null, { status: 204, headers: result.cookie ? { 'Set-Cookie': result.cookie } : {} })
103
+ }
104
+ ```
105
+
106
+ - 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.
107
+ - 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.
108
+ - **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.
109
+ - 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.
110
+ - 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.
111
+
83
112
  ## Commands
84
113
 
85
114
  ```bash
@@ -1,4 +1,27 @@
1
- import { type Endpoint } from 'payload';
1
+ import { type Endpoint, type PayloadRequest } from 'payload';
2
2
  import { revokeSessions } from './sessions.js';
3
+ /** What a switch came to. A refusal carries the endpoint's `reason` (`needsCode` included) and its English message. */
4
+ export type SwitchResult = {
5
+ ok: true;
6
+ account: string;
7
+ hat: string; /** The Set-Cookie value for the new session, or null when the hat changed on the same account. */
8
+ cookie: string | null;
9
+ } | {
10
+ ok: false;
11
+ status: number;
12
+ reason: string;
13
+ message: string;
14
+ };
15
+ /** The input of a switch: the same three fields the endpoint reads from its body. */
16
+ export type SwitchInput = {
17
+ account?: unknown;
18
+ hat?: unknown;
19
+ code?: unknown;
20
+ };
21
+ /**
22
+ * The one switch, shared by POST /api/hats/switch and `switchSession`, so the two can't drift. It acts only for
23
+ * `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
24
+ */
25
+ export declare function runSwitch(req: PayloadRequest, input: SwitchInput | null | undefined): Promise<SwitchResult>;
3
26
  export declare const hatEndpoints: Endpoint[];
4
27
  export { revokeSessions };
package/dist/endpoints.js CHANGED
@@ -110,6 +110,170 @@ const me = {
110
110
  });
111
111
  },
112
112
  };
113
+ /**
114
+ * The one switch, shared by POST /api/hats/switch and `switchSession`, so the two can't drift. It acts only for
115
+ * `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
116
+ */
117
+ export async function runSwitch(req, input) {
118
+ try {
119
+ return await switchCore(req, input ?? {});
120
+ }
121
+ catch (error) {
122
+ if (error instanceof APIError) {
123
+ const reason = error.data?.reason;
124
+ return { ok: false, status: error.status, reason: typeof reason === 'string' ? reason : 'failed', message: error.message };
125
+ }
126
+ req.payload?.logger?.warn({ err: error }, 'Hats: switch refused after an unexpected error');
127
+ return { ok: false, status: 500, reason: 'failed', message: 'Switching didn’t work. Try again.' };
128
+ }
129
+ }
130
+ /** The origins this site answers as: the one the request arrived on, and the configured server URL. */
131
+ function ownOrigins(req) {
132
+ const out = [];
133
+ for (const u of [req.url, req.payload?.config?.serverURL]) {
134
+ try {
135
+ if (u)
136
+ out.push(new URL(u).origin);
137
+ }
138
+ catch {
139
+ /* an unreadable address adds no origin, so a mismatch is refused */
140
+ }
141
+ }
142
+ return out;
143
+ }
144
+ /** Reads a header from a Headers instance or a plain object (any key case). Null for anything else, which is refused as cross-site. */
145
+ function headerReader(h) {
146
+ if (h instanceof Headers)
147
+ return (name) => h.get(name);
148
+ const proto = h && typeof h === 'object' ? Object.getPrototypeOf(h) : undefined;
149
+ if (proto !== Object.prototype && proto !== null)
150
+ return null;
151
+ const entries = Object.entries(h);
152
+ // Header values are strings (or lists of them, as Node gives them); a function or anything else means this isn't headers.
153
+ const plain = (v) => v == null || typeof v === 'string' || (Array.isArray(v) && v.every((x) => typeof x === 'string'));
154
+ if (!entries.every(([, v]) => plain(v)))
155
+ return null;
156
+ return (name) => {
157
+ const hit = entries.find(([k]) => k.toLowerCase() === name);
158
+ if (!hit)
159
+ return null;
160
+ const v = hit[1];
161
+ return Array.isArray(v) ? v.join(', ') : v == null ? null : String(v);
162
+ };
163
+ }
164
+ /** A switch only comes from the site's own POST: any other method, a foreign Origin or a Sec-Fetch-Site other than same-origin is refused. */
165
+ function refuseCrossSite(req) {
166
+ if (String(req.method ?? '').toUpperCase() !== 'POST')
167
+ refuse('Switching needs a POST from this site.', 405, 'notPost');
168
+ const header = headerReader(req.headers);
169
+ if (!header)
170
+ return refuse('Switching must come from this site.', 403, 'crossSite'); // no headers to check, so no way to tell: refused
171
+ const origin = header('origin');
172
+ if (origin != null && !ownOrigins(req).includes(origin))
173
+ refuse('Switching must come from this site.', 403, 'crossSite');
174
+ const fetchSite = header('sec-fetch-site');
175
+ if (fetchSite != null && fetchSite !== 'same-origin')
176
+ refuse('Switching must come from this site.', 403, 'crossSite');
177
+ }
178
+ async function switchCore(req, body) {
179
+ refuseCrossSite(req);
180
+ const { opts, full, state, person } = await actor(req);
181
+ await blockedReason(req, opts);
182
+ const current = String(full.id);
183
+ const to = body.account == null || body.account === '' ? current : String(body.account);
184
+ let link = null;
185
+ if (to !== current) {
186
+ link = await sharedLink(req.payload, current, to, req);
187
+ if (!link)
188
+ refuse('That account isn’t linked to this one.', 403, 'notLinked');
189
+ }
190
+ const target = to === current ? full : await loadUser(req, to);
191
+ if (!target)
192
+ refuse('That account isn’t linked to this one.', 403, 'notLinked');
193
+ // Direct login refuses a locked account, so a switch into one is refused too.
194
+ const lockUntil = to === current ? null : target.lockUntil;
195
+ if (lockUntil != null && new Date(lockUntil).getTime() > Date.now())
196
+ refuse('That account is locked. Try again later.', 403, 'locked');
197
+ // Direct login refuses an unverified account when the collection verifies emails, so a switch does too.
198
+ const usersAuth = req.payload.collections[opts.users].config.auth;
199
+ if (to !== current && usersAuth.verify && target._verified === false)
200
+ refuse('That account’s email isn’t confirmed yet.', 403, 'unverified');
201
+ const { linked } = await linkedAccounts(req, current);
202
+ if (!(opts.showSwitch ?? defaultShow)({ user: full, hats: opts.hatsOf(full), linked }))
203
+ refuse('Switching isn’t available for this account.', 403, 'notAvailable');
204
+ const hats = opts.hatsOf(target);
205
+ const hat = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
206
+ if (!hat)
207
+ refuse('Choose one of that account’s hats.', 400, 'chooseHat');
208
+ const s = await sessionBySid(req.payload, state.sid, req);
209
+ const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
210
+ const steppedUp = { ...(s?.steppedUp ?? {}) };
211
+ let gaveCode = false;
212
+ const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
213
+ const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
214
+ if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
215
+ if (!opts.stepUp)
216
+ refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
217
+ // Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
218
+ const stepUp = opts.stepUp;
219
+ const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId };
220
+ if (!(await exactlyTrue(() => stepUp.available(target, ctx))))
221
+ refuse('Set up two-step sign-in on that account first.', 403, 'setUpTwoStep');
222
+ const code = typeof body.code === 'string' ? body.code.trim() : '';
223
+ if (!code)
224
+ return { ok: false, status: 401, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' };
225
+ if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
226
+ refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
227
+ steppedUp[memoryKey(opts, to, setId)] = new Date().toISOString();
228
+ gaveCode = true;
229
+ }
230
+ const users = req.payload.collections[opts.users].config;
231
+ if (to === current) {
232
+ await asPlugin(req, async () => {
233
+ if (s)
234
+ await req.payload.update({ collection: SESSIONS, id: s.id, data: { hat: hat.id, steppedUp }, overrideAccess: true, req });
235
+ else
236
+ await req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req });
237
+ });
238
+ await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
239
+ return { ok: true, account: to, hat: hat.id, cookie: null };
240
+ }
241
+ // Another account: a fresh Payload session for it, then this one ends.
242
+ const own = person === to;
243
+ const { sid } = await addSessionToUser({ collectionConfig: users, payload: req.payload, req, user: target });
244
+ if (!sid)
245
+ refuse('Switching accounts needs Payload sessions (auth.useSessions).', 500, 'noSessions');
246
+ await asPlugin(req, () => req.payload.create({
247
+ collection: SESSIONS,
248
+ data: { sid, user: to, via: own ? null : person, link: own ? null : link, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) },
249
+ overrideAccess: true,
250
+ req,
251
+ }));
252
+ await revokeSid(req.payload, current, state.sid, req);
253
+ if (s)
254
+ await tombstone(req.payload, s.id, req);
255
+ else
256
+ await asPlugin(req, () => req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, revokedAt: new Date().toISOString(), expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req }));
257
+ await cleanupSessions(req.payload, req).catch((err) => req.payload.logger.warn({ err }, 'Hats: session clean-up skipped'));
258
+ const { token } = await jwtSign({
259
+ fieldsToSign: getFieldsToSign({ collectionConfig: users, email: String(target.email ?? ''), sid, user: target }),
260
+ secret: req.payload.secret,
261
+ tokenExpiration: users.auth.tokenExpiration,
262
+ });
263
+ const cookie = generateCookie({
264
+ name: `${req.payload.config.cookiePrefix}-token`,
265
+ value: token,
266
+ path: '/',
267
+ httpOnly: true,
268
+ secure: users.auth.cookies.secure,
269
+ sameSite: typeof users.auth.cookies.sameSite === 'string' ? users.auth.cookies.sameSite : 'Lax',
270
+ domain: users.auth.cookies.domain ?? undefined,
271
+ expires: new Date(Date.now() + users.auth.tokenExpiration * 1000),
272
+ returnCookieAsObject: false,
273
+ });
274
+ await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
275
+ return { ok: true, account: to, hat: hat.id, cookie };
276
+ }
113
277
  /**
114
278
  * POST /api/hats/switch { account?, hat, code? }: wear another hat, on this account or another approved account in
115
279
  * the same set. A sensitive hat needs that account's second factor unless it was given here recently.
@@ -119,95 +283,12 @@ const switchHat = {
119
283
  method: 'post',
120
284
  handler: async (req) => {
121
285
  await addDataAndFileToRequest(req);
122
- const { opts, full, state, person } = await actor(req);
123
- await blockedReason(req, opts);
124
- const body = (req.data ?? {});
125
- const current = String(full.id);
126
- const to = body.account == null || body.account === '' ? current : String(body.account);
127
- let link = null;
128
- if (to !== current) {
129
- link = await sharedLink(req.payload, current, to, req);
130
- if (!link)
131
- refuse('That account isn’t linked to this one.', 403, 'notLinked');
132
- }
133
- const target = to === current ? full : await loadUser(req, to);
134
- if (!target)
135
- refuse('That account isn’t linked to this one.', 403, 'notLinked');
136
- const { linked } = await linkedAccounts(req, current);
137
- if (!(opts.showSwitch ?? defaultShow)({ user: full, hats: opts.hatsOf(full), linked }))
138
- refuse('Switching isn’t available for this account.', 403, 'notAvailable');
139
- const hats = opts.hatsOf(target);
140
- const hat = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
141
- if (!hat)
142
- refuse('Choose one of that account’s hats.', 400, 'chooseHat');
143
- const s = await sessionBySid(req.payload, state.sid, req);
144
- const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
145
- const steppedUp = { ...(s?.steppedUp ?? {}) };
146
- let gaveCode = false;
147
- const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
148
- const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
149
- if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
150
- if (!opts.stepUp)
151
- refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
152
- // Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
153
- const stepUp = opts.stepUp;
154
- const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId };
155
- if (!(await exactlyTrue(() => stepUp.available(target, ctx))))
156
- refuse('Set up two-step sign-in on that account first.', 403, 'setUpTwoStep');
157
- const code = typeof body.code === 'string' ? body.code.trim() : '';
158
- if (!code)
159
- return json({ ok: false, needsCode: true, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' }, 401);
160
- if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
161
- refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
162
- steppedUp[memoryKey(opts, to, setId)] = new Date().toISOString();
163
- gaveCode = true;
164
- }
165
- const users = req.payload.collections[opts.users].config;
166
- if (to === current) {
167
- await asPlugin(req, async () => {
168
- if (s)
169
- await req.payload.update({ collection: SESSIONS, id: s.id, data: { hat: hat.id, steppedUp }, overrideAccess: true, req });
170
- else
171
- await req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req });
172
- });
173
- await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
174
- return json({ ok: true, account: to, hat: hat.id, reload: true });
175
- }
176
- // Another account: a fresh Payload session for it, then this one ends.
177
- const own = person === to;
178
- const { sid } = await addSessionToUser({ collectionConfig: users, payload: req.payload, req, user: target });
179
- if (!sid)
180
- refuse('Switching accounts needs Payload sessions (auth.useSessions).', 500);
181
- await asPlugin(req, () => req.payload.create({
182
- collection: SESSIONS,
183
- data: { sid, user: to, via: own ? null : person, link: own ? null : link, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) },
184
- overrideAccess: true,
185
- req,
186
- }));
187
- await revokeSid(req.payload, current, state.sid, req);
188
- if (s)
189
- await tombstone(req.payload, s.id, req);
190
- else
191
- await asPlugin(req, () => req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, revokedAt: new Date().toISOString(), expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req }));
192
- await cleanupSessions(req.payload, req).catch((err) => req.payload.logger.warn({ err }, 'Hats: session clean-up skipped'));
193
- const { token } = await jwtSign({
194
- fieldsToSign: getFieldsToSign({ collectionConfig: users, email: String(target.email ?? ''), sid, user: target }),
195
- secret: req.payload.secret,
196
- tokenExpiration: users.auth.tokenExpiration,
197
- });
198
- const cookie = generateCookie({
199
- name: `${req.payload.config.cookiePrefix}-token`,
200
- value: token,
201
- path: '/',
202
- httpOnly: true,
203
- secure: users.auth.cookies.secure,
204
- sameSite: typeof users.auth.cookies.sameSite === 'string' ? users.auth.cookies.sameSite : 'Lax',
205
- domain: users.auth.cookies.domain ?? undefined,
206
- expires: new Date(Date.now() + users.auth.tokenExpiration * 1000),
207
- returnCookieAsObject: false,
208
- });
209
- await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
210
- return json({ ok: true, account: to, hat: hat.id, reload: true }, 200, [cookie]);
286
+ const result = await runSwitch(req, (req.data ?? {}));
287
+ if (result.ok)
288
+ return json({ ok: true, account: result.account, hat: result.hat, reload: true }, 200, result.cookie ? [result.cookie] : []);
289
+ if (result.reason === 'needsCode')
290
+ return json({ ok: false, needsCode: true, reason: 'needsCode', message: result.message }, 401);
291
+ return refuse(result.message, result.status, result.reason);
211
292
  },
212
293
  };
213
294
  const expiry = (seconds) => new Date(Date.now() + seconds * 1000).toISOString();
package/dist/index.d.ts CHANGED
@@ -1,8 +1,24 @@
1
- import type { Plugin } from 'payload';
1
+ import type { PayloadRequest, Plugin } from 'payload';
2
+ import { type SwitchInput, type SwitchResult } from './endpoints.js';
2
3
  import { type HatsOptions } from './types.js';
3
4
  export { hatsStateOf } from './state.js';
4
5
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
5
6
  export { LINKS, MEMBERS, SESSIONS } from './types.js';
7
+ export type { SwitchInput, SwitchResult };
8
+ /**
9
+ * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
10
+ * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
11
+ * the old session's revoke), and has no option that skips one. It acts only for `req.user`: with nobody signed in it
12
+ * is refused (`signIn`, 401). It never throws for a refusal. An error from a site hook is a refusal too.
13
+ *
14
+ * On `{ ok: true }` the route must send `cookie` back as `Set-Cookie`. Call it only from a same-origin POST, never
15
+ * from a GET: a GET can be started by a link on another site, and `SameSite=Lax` still sends the sign-in cookie on it.
16
+ */
17
+ export declare const switchSession: (req: PayloadRequest, input: {
18
+ account?: string | number | null;
19
+ hat?: string;
20
+ code?: string;
21
+ }) => Promise<SwitchResult>;
6
22
  export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, StepUpContext } from './types.js';
7
23
  /**
8
24
  * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
package/dist/index.js CHANGED
@@ -1,11 +1,21 @@
1
1
  import { hatCollections } from './collections.js';
2
- import { hatEndpoints } from './endpoints.js';
2
+ import { hatEndpoints, runSwitch } from './endpoints.js';
3
3
  import { revokeSessions, wrapStrategies } from './sessions.js';
4
4
  import { asPlugin } from './state.js';
5
5
  import { MEMBERS, SESSIONS } from './types.js';
6
6
  export { hatsStateOf } from './state.js';
7
7
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
8
8
  export { LINKS, MEMBERS, SESSIONS } from './types.js';
9
+ /**
10
+ * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
11
+ * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
12
+ * the old session's revoke), and has no option that skips one. It acts only for `req.user`: with nobody signed in it
13
+ * is refused (`signIn`, 401). It never throws for a refusal. An error from a site hook is a refusal too.
14
+ *
15
+ * On `{ ok: true }` the route must send `cookie` back as `Set-Cookie`. Call it only from a same-origin POST, never
16
+ * from a GET: a GET can be started by a link on another site, and `SameSite=Lax` still sends the sign-in cookie on it.
17
+ */
18
+ export const switchSession = (req, input) => runSwitch(req, input);
9
19
  /**
10
20
  * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
11
21
  * holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Linked accounts and role hats for Payload: one person switches between their approved accounts, and acts in one role at a time, with a second factor before switching up.",
5
5
  "keywords": [
6
6
  "payload",