@extantape/payload-plugin-hats 0.3.1 → 0.5.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 +61 -4
- package/dist/collections.d.ts +1 -1
- package/dist/collections.js +67 -15
- package/dist/endpoints.d.ts +24 -1
- package/dist/endpoints.js +392 -144
- package/dist/index.d.ts +18 -2
- package/dist/index.js +56 -16
- package/dist/sessions.js +23 -16
- package/dist/state.d.ts +68 -4
- package/dist/state.js +165 -6
- package/dist/types.d.ts +9 -1
- package/dist/types.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,12 +7,13 @@ Linked accounts and role hats for Payload. One person links their accounts and s
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
9
9
|
- **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set. Unlinking is self-serve and immediate.
|
|
10
|
+
- **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.
|
|
10
11
|
- **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
|
|
12
|
+
- **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
13
|
- **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
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.
|
|
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.
|
|
15
|
-
- **Link limits.** Pass `limit` to rate-limit link requests
|
|
15
|
+
- **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).
|
|
16
|
+
- **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.
|
|
16
17
|
|
|
17
18
|
Needs Payload sessions (`auth.useSessions`, on by default).
|
|
18
19
|
|
|
@@ -56,7 +57,7 @@ Endpoints, under the API route:
|
|
|
56
57
|
|
|
57
58
|
- `GET /hats` lists the acting account, its hats and its linked accounts.
|
|
58
59
|
- `POST /hats/switch { account?, hat, code? }` switches hat or account.
|
|
59
|
-
- `POST /hats/link { email }` asks to link another account.
|
|
60
|
+
- `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.
|
|
60
61
|
- `GET` and `POST /hats/confirm` handle the email confirmation.
|
|
61
62
|
- `POST /hats/unlink { account? }` takes an account out of the set.
|
|
62
63
|
|
|
@@ -80,6 +81,62 @@ Colors and sizes come from `--hats-ink`, `--hats-paper`, `--hats-line`, `--hats-
|
|
|
80
81
|
|
|
81
82
|
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
83
|
|
|
84
|
+
## Switching from your own route
|
|
85
|
+
|
|
86
|
+
`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.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
// app/api/enter-admin/route.ts (Next.js). Your own POST route, not the picker.
|
|
90
|
+
import { getPayload, type PayloadRequest } from 'payload'
|
|
91
|
+
import config from '@payload-config'
|
|
92
|
+
import { switchSession } from '@extantape/payload-plugin-hats'
|
|
93
|
+
|
|
94
|
+
export async function POST(request: Request) {
|
|
95
|
+
const payload = await getPayload({ config })
|
|
96
|
+
const { user } = await payload.auth({ headers: request.headers }) // the person's own sign-in cookie
|
|
97
|
+
if (!user) return Response.json({ reason: 'signIn' }, { status: 401 })
|
|
98
|
+
const { account, hat, code } = await request.json() // ids from your own screen; code only when it asked for one
|
|
99
|
+
// The plugin reads method, Origin and Sec-Fetch-Site from this request and refuses a cross-site call.
|
|
100
|
+
const req = { payload, user, headers: request.headers, method: request.method, url: request.url } as unknown as PayloadRequest
|
|
101
|
+
const result = await switchSession(req, { account, hat, code })
|
|
102
|
+
if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status }) // needsCode, wrongCode, blocked, notLinked, locked ...
|
|
103
|
+
return new Response(null, { status: 204, headers: result.cookie ? { 'Set-Cookie': result.cookie } : {} })
|
|
104
|
+
}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
- 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.
|
|
108
|
+
- 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.
|
|
109
|
+
- **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.
|
|
110
|
+
- 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.
|
|
111
|
+
- 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.
|
|
112
|
+
|
|
113
|
+
## Upgrading from 0.4.0
|
|
114
|
+
|
|
115
|
+
Sets already approved keep working, and requests still pending from 0.4.0 complete through their old links with the same confirmations and approval.
|
|
116
|
+
|
|
117
|
+
**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`.
|
|
118
|
+
|
|
119
|
+
**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.
|
|
120
|
+
|
|
121
|
+
Everything else that changes for a host, in full:
|
|
122
|
+
|
|
123
|
+
1. Regenerate types with `payload generate:types` (new `hat-requests` collection, new export `REQUESTS`).
|
|
124
|
+
2. Review a custom `reasons.linkSent` text: it shouldn't name the address.
|
|
125
|
+
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.
|
|
126
|
+
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.
|
|
127
|
+
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.
|
|
128
|
+
6. Key `limit` by address as well as person.
|
|
129
|
+
7. Startup refuses a config that already has a `hat-requests` collection.
|
|
130
|
+
8. A `hatsInternal` or `hatsDissolving` key in `context` means nothing.
|
|
131
|
+
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`.
|
|
132
|
+
10. If your users collection has afterDelete hooks, the plugin's now runs first, and only for a delete that happened.
|
|
133
|
+
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.
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
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.
|
|
137
|
+
|
|
138
|
+
The changelog lists every change.
|
|
139
|
+
|
|
83
140
|
## Commands
|
|
84
141
|
|
|
85
142
|
```bash
|
package/dist/collections.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type CollectionConfig } from 'payload';
|
|
2
2
|
import { type ResolvedHatsOptions } from './types.js';
|
|
3
|
-
export declare function hatCollections(opts: ResolvedHatsOptions): CollectionConfig[];
|
|
3
|
+
export declare function hatCollections(opts: ResolvedHatsOptions, sql: boolean): CollectionConfig[];
|
package/dist/collections.js
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
|
-
import { APIError } from 'payload';
|
|
1
|
+
import { APIError, validations } from 'payload';
|
|
2
2
|
import { exactlyTrue } from './access.js';
|
|
3
3
|
import { dissolveIfAlone, revokeSessions } from './sessions.js';
|
|
4
|
-
import { hatsStateOf, idOf } from './state.js';
|
|
5
|
-
import { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
6
|
-
const internal =
|
|
4
|
+
import { hatsStateOf, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
|
|
5
|
+
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
6
|
+
const internal = isInternal;
|
|
7
|
+
/**
|
|
8
|
+
* Required on every write, but nullable in the database. On SQL databases the account's foreign key sets these to
|
|
9
|
+
* null as the account is deleted; a NOT NULL column would refuse that, so the delete failed. The plugin removes those
|
|
10
|
+
* rows straight after, in the account's afterDelete.
|
|
11
|
+
*/
|
|
12
|
+
const requiredOnWrite = (value, options) => validations.relationship(value, { ...options, required: true });
|
|
13
|
+
/**
|
|
14
|
+
* An account relationship every row must have. On MongoDB it stays `required`, as in 0.4.0, so its indexes come out
|
|
15
|
+
* exactly as 0.4.0 built them (Payload makes a unique index sparse when the field isn't required, and a database that
|
|
16
|
+
* already has the 0.4.0 index then refuses to start with `ensureIndexes`). MongoDB has no foreign keys, so nothing
|
|
17
|
+
* there needs the column to take null. On SQL databases the column is nullable and the rule moves to validation.
|
|
18
|
+
*/
|
|
19
|
+
const requiredAccount = (sql) => (sql ? { validate: requiredOnWrite } : { required: true });
|
|
7
20
|
/**
|
|
8
21
|
* Whether the request's user may approve links. A person never approves their own link: an approver who is (or
|
|
9
22
|
* who signed in as) a member of the set is refused, so the owner's own links need another approver. Only an exact
|
|
@@ -16,7 +29,7 @@ async function approver(opts, req) {
|
|
|
16
29
|
const ask = opts.canApproveLinks;
|
|
17
30
|
return exactlyTrue(() => ask({ req, user }));
|
|
18
31
|
}
|
|
19
|
-
export function hatCollections(opts) {
|
|
32
|
+
export function hatCollections(opts, sql) {
|
|
20
33
|
const canApprove = ({ req }) => approver(opts, req);
|
|
21
34
|
const never = () => false;
|
|
22
35
|
const links = {
|
|
@@ -41,7 +54,7 @@ export function hatCollections(opts) {
|
|
|
41
54
|
access: { read: canApprove, create: never, update: canApprove, delete: canApprove },
|
|
42
55
|
fields: [
|
|
43
56
|
{ name: 'link', type: 'relationship', relationTo: LINKS, required: true, index: true, label: 'Linked set', admin: { readOnly: true, description: 'Filter the list by this set to see every account in it.' } },
|
|
44
|
-
{ name: 'user', type: 'relationship', relationTo: opts.users,
|
|
57
|
+
{ name: 'user', type: 'relationship', relationTo: opts.users, ...requiredAccount(sql), unique: true, admin: { readOnly: true } },
|
|
45
58
|
{
|
|
46
59
|
name: 'status',
|
|
47
60
|
type: 'select',
|
|
@@ -62,7 +75,7 @@ export function hatCollections(opts) {
|
|
|
62
75
|
],
|
|
63
76
|
hooks: {
|
|
64
77
|
beforeChange: [
|
|
65
|
-
async ({ data, originalDoc, operation, req }) => {
|
|
78
|
+
ownHook(async ({ data, originalDoc, operation, req }) => {
|
|
66
79
|
if (internal(req))
|
|
67
80
|
return data;
|
|
68
81
|
// Outside the plugin's own endpoints, the only change allowed is an approver approving a confirmed account.
|
|
@@ -88,25 +101,34 @@ export function hatCollections(opts) {
|
|
|
88
101
|
});
|
|
89
102
|
if (mine.totalDocs > 0)
|
|
90
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);
|
|
91
113
|
return { ...data, approvedBy: me.id, approvedAt: new Date().toISOString() };
|
|
92
|
-
},
|
|
114
|
+
}),
|
|
93
115
|
],
|
|
94
116
|
afterChange: [
|
|
95
|
-
async ({ doc, previousDoc, operation, req }) => {
|
|
117
|
+
ownHook(async ({ doc, previousDoc, operation, req }) => {
|
|
96
118
|
if (operation === 'update' && previousDoc?.status !== 'approved' && doc.status === 'approved' && !internal(req))
|
|
97
119
|
await opts.onEvent?.({ type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
|
|
98
|
-
},
|
|
120
|
+
}),
|
|
99
121
|
],
|
|
100
122
|
afterDelete: [
|
|
101
|
-
async ({ doc, req }) => {
|
|
123
|
+
ownHook(async ({ doc, req }) => {
|
|
102
124
|
const link = idOf(doc.link);
|
|
103
125
|
const account = idOf(doc.user);
|
|
104
126
|
await revokeSessions(req.payload, { and: [{ link: { equals: link } }, { or: [{ user: { equals: account } }, { via: { equals: account } }] }] }, 'unlinked', req);
|
|
105
127
|
if (!internal(req))
|
|
106
|
-
await
|
|
107
|
-
if (!req
|
|
128
|
+
await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: req.user ? String(req.user.id) : null });
|
|
129
|
+
if (!isDissolving(req))
|
|
108
130
|
await dissolveIfAlone(req.payload, link, req);
|
|
109
|
-
},
|
|
131
|
+
}),
|
|
110
132
|
],
|
|
111
133
|
},
|
|
112
134
|
};
|
|
@@ -127,5 +149,35 @@ export function hatCollections(opts) {
|
|
|
127
149
|
{ name: 'revokedAt', type: 'date', index: true },
|
|
128
150
|
],
|
|
129
151
|
};
|
|
130
|
-
|
|
152
|
+
// A link request waiting for the other account to confirm. Nobody reads or writes these but the plugin, so the
|
|
153
|
+
// person asking can't tell from them whether the address they gave has an account. One is written for every
|
|
154
|
+
// request, whatever the address; `account` is set only when an invitation was sent, and only one invitation to an
|
|
155
|
+
// account is open at a time, which the unique `holds` field enforces.
|
|
156
|
+
const requests = {
|
|
157
|
+
slug: REQUESTS,
|
|
158
|
+
admin: { hidden: true },
|
|
159
|
+
access: { read: never, create: never, update: never, delete: never },
|
|
160
|
+
fields: [
|
|
161
|
+
{ name: 'requestedBy', type: 'relationship', relationTo: opts.users, ...requiredAccount(sql), index: true },
|
|
162
|
+
{ name: 'account', type: 'relationship', relationTo: opts.users, index: true },
|
|
163
|
+
// Unique, so the database keeps it to one open invitation per account even when requests arrive together:
|
|
164
|
+
// `account:<id>` while an invitation is open, otherwise a random `none:` value that holds nothing.
|
|
165
|
+
{ name: 'holds', type: 'text', required: true, unique: true, index: true },
|
|
166
|
+
{ name: 'tokenHash', type: 'text', index: true },
|
|
167
|
+
{ name: 'expiresAt', type: 'date', required: true, index: true },
|
|
168
|
+
// The asker's set when they asked, so a confirmation can't put the account into a set the invitation came before.
|
|
169
|
+
{ name: 'link', type: 'text' },
|
|
170
|
+
],
|
|
171
|
+
hooks: {
|
|
172
|
+
beforeChange: [
|
|
173
|
+
ownHook(({ data, req }) => {
|
|
174
|
+
// Server code with overrideAccess included: a request written outside the plugin could be confirmed.
|
|
175
|
+
if (!internal(req))
|
|
176
|
+
throw new APIError('Only the hats plugin writes link requests.', 403, undefined, true);
|
|
177
|
+
return data;
|
|
178
|
+
}),
|
|
179
|
+
],
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
return [links, members, sessions, requests];
|
|
131
183
|
}
|
package/dist/endpoints.d.ts
CHANGED
|
@@ -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 };
|