@extantape/payload-plugin-hats 0.4.0 → 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 +31 -3
- package/dist/collections.d.ts +1 -1
- package/dist/collections.js +67 -15
- package/dist/endpoints.js +222 -55
- package/dist/index.d.ts +1 -1
- package/dist/index.js +45 -15
- 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
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
|
|
|
@@ -109,6 +110,33 @@ export async function POST(request: Request) {
|
|
|
109
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.
|
|
110
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.
|
|
111
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
|
+
|
|
112
140
|
## Commands
|
|
113
141
|
|
|
114
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.js
CHANGED
|
@@ -3,8 +3,8 @@ import { addSessionToUser, generateCookie } from 'payload/shared';
|
|
|
3
3
|
import { blockedBy, exactlyTrue } from './access.js';
|
|
4
4
|
import { cleanupSessions, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
|
|
5
5
|
import { memoryKey, needsStepUp, remembered } from './stepup.js';
|
|
6
|
-
import { asPlugin, hashToken, hatsOptions, hatsStateOf, idOf, newToken } from './state.js';
|
|
7
|
-
import { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
6
|
+
import { asPlugin, DISSOLVING, hashToken, hatsOptions, hatsStateOf, idOf, newToken, relId, removeWhere, tell, trackWork, unmarked, withMark } from './state.js';
|
|
7
|
+
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
8
8
|
const json = (body, status = 200, cookies = []) => {
|
|
9
9
|
const headers = new Headers({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
10
10
|
for (const c of cookies)
|
|
@@ -37,7 +37,9 @@ async function members(req, link) {
|
|
|
37
37
|
}
|
|
38
38
|
async function membershipOf(req, userId) {
|
|
39
39
|
const { docs } = await req.payload.find({ collection: MEMBERS, where: { user: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
40
|
-
|
|
40
|
+
const row = docs[0] ?? null;
|
|
41
|
+
// Only a row for exactly this account: on MongoDB the text "null" can match a row whose account was cleared.
|
|
42
|
+
return row && row.user != null && idOf(row.user) === userId ? row : null;
|
|
41
43
|
}
|
|
42
44
|
/** The other approved accounts in the acting account's set, with their hats. */
|
|
43
45
|
async function linkedAccounts(req, userId) {
|
|
@@ -181,6 +183,9 @@ async function switchCore(req, body) {
|
|
|
181
183
|
await blockedReason(req, opts);
|
|
182
184
|
const current = String(full.id);
|
|
183
185
|
const to = body.account == null || body.account === '' ? current : String(body.account);
|
|
186
|
+
// Only an id exactly as the account has it. Anything else answers as an account that isn't linked, before any query.
|
|
187
|
+
if (to !== current && !exactId(req, opts, body.account))
|
|
188
|
+
refuse('That account isn’t linked to this one.', 403, 'notLinked');
|
|
184
189
|
let link = null;
|
|
185
190
|
if (to !== current) {
|
|
186
191
|
link = await sharedLink(req.payload, current, to, req);
|
|
@@ -292,8 +297,18 @@ const switchHat = {
|
|
|
292
297
|
},
|
|
293
298
|
};
|
|
294
299
|
const expiry = (seconds) => new Date(Date.now() + seconds * 1000).toISOString();
|
|
295
|
-
const SENT = 'If that account can be linked, we’ve emailed it a link to confirm.
|
|
296
|
-
|
|
300
|
+
const SENT = 'If that address belongs to an account that can be linked, we’ve emailed it a link to confirm. Once it’s confirmed, we’ll email you to confirm from your side, and then an administrator reviews the link.';
|
|
301
|
+
const confirmLink = async (req, opts, token) => opts.confirmURL ? String(await unmarked(req, () => opts.confirmURL({ req, token }))) : `${new URL(req.url ?? 'http://localhost').origin}${req.payload.config.routes.api}/hats/confirm?token=${token}`;
|
|
302
|
+
/** Open link requests one account may have at once. Counted the same whatever the addresses were. */
|
|
303
|
+
const pendingCap = (opts) => opts.maxLinked * 2;
|
|
304
|
+
/**
|
|
305
|
+
* POST /api/hats/link { email }: ask to link the acting account with another. The person asking learns nothing
|
|
306
|
+
* about the address: the answer, the time it takes, their own email, the records they can read and the records
|
|
307
|
+
* written for them are the same whether or not it has an account, whatever state that account is in. Only the
|
|
308
|
+
* other account hears about it, and nothing changes on the asker's side until that account confirms.
|
|
309
|
+
*/
|
|
310
|
+
/** What a request's unique `holds` is: the account invited, or a value of its own that holds nothing. */
|
|
311
|
+
const holdFor = (account) => (account ? `account:${String(account.id)}` : `none:${newToken()}`);
|
|
297
312
|
const requestLink = {
|
|
298
313
|
path: '/hats/link',
|
|
299
314
|
method: 'post',
|
|
@@ -311,57 +326,94 @@ const requestLink = {
|
|
|
311
326
|
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
312
327
|
const me = String(full.id);
|
|
313
328
|
const now = new Date();
|
|
329
|
+
// Everything up to here depends only on the asker and what they typed. From here on the answer waits for the
|
|
330
|
+
// same fixed time whatever happens, so how long the work takes says nothing about the address.
|
|
331
|
+
const answer = new Promise((resolve) => setTimeout(resolve, opts.linkAnswerMs));
|
|
314
332
|
await asPlugin(req, async () => {
|
|
315
333
|
// Requests nobody confirmed in time don't hold anyone up.
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] },
|
|
319
|
-
overrideAccess: true,
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
334
|
+
// Best effort: what isn't removed now goes on a later request, and the request goes on either way.
|
|
335
|
+
for (const swept of [
|
|
336
|
+
await req.payload.delete({ collection: MEMBERS, where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] }, overrideAccess: true, showHiddenFields: true, req }),
|
|
337
|
+
await req.payload.delete({ collection: REQUESTS, where: { expiresAt: { less_than: now.toISOString() } }, overrideAccess: true, req }),
|
|
338
|
+
])
|
|
339
|
+
if (swept.errors?.length)
|
|
340
|
+
req.payload.logger.warn({ msg: 'Hats: some expired link requests were not removed; a later request retries' });
|
|
323
341
|
});
|
|
324
342
|
const mine = await membershipOf(req, me);
|
|
325
343
|
const already = mine ? (await members(req, idOf(mine.link))).length : 0;
|
|
326
|
-
if (already + (mine ? 1 : 2) > opts.maxLinked)
|
|
344
|
+
if (already + (mine ? 1 : 2) > opts.maxLinked) {
|
|
345
|
+
await answer;
|
|
327
346
|
refuse(`A set can hold at most ${opts.maxLinked} accounts.`, 400, 'setFull');
|
|
328
|
-
|
|
329
|
-
const
|
|
330
|
-
if (
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
347
|
+
}
|
|
348
|
+
const open = await req.payload.count({ collection: REQUESTS, where: { requestedBy: { equals: me } }, overrideAccess: true, req });
|
|
349
|
+
if (open.totalDocs >= pendingCap(opts)) {
|
|
350
|
+
await answer;
|
|
351
|
+
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
352
|
+
}
|
|
353
|
+
const work = async () => {
|
|
354
|
+
const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
355
|
+
const found = docs[0];
|
|
356
|
+
let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
|
|
357
|
+
// One record for every request, with the same fields. Only a real invitation's token can ever be used.
|
|
334
358
|
const token = newToken();
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
359
|
+
const hours = opts.confirmHours;
|
|
360
|
+
const hold = holdFor(null);
|
|
361
|
+
const request = (await asPlugin(req, () => req.payload.create({
|
|
362
|
+
collection: REQUESTS,
|
|
363
|
+
data: { requestedBy: relId(req.payload, opts.users, full.id), account: null, holds: hold, tokenHash: hashToken(token), expiresAt: new Date(now.getTime() + hours * 3_600_000).toISOString(), link: mine ? idOf(mine.link) : null },
|
|
338
364
|
overrideAccess: true,
|
|
339
365
|
req,
|
|
340
|
-
});
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
366
|
+
})));
|
|
367
|
+
// One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
|
|
368
|
+
// rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
|
|
369
|
+
// the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
|
|
370
|
+
// means no invitation, so the asker sees the same thing either way.
|
|
371
|
+
const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
|
|
372
|
+
const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
|
|
373
|
+
if (!claimed)
|
|
374
|
+
target = null;
|
|
375
|
+
// The asker's own note is the same every time and leaves the address out, so it can't tell them anything.
|
|
376
|
+
try {
|
|
377
|
+
await opts.sendEmail({
|
|
378
|
+
payload: req.payload,
|
|
379
|
+
to: String(full.email),
|
|
380
|
+
subject: 'You asked to link an account',
|
|
381
|
+
text: `You asked to link ${labelOf(full)} with another account, so one person can switch between them.\n\nIf the address you entered belongs to an account that can be linked, we’ve emailed it a link to confirm within ${hours} hours. Once it’s confirmed, we’ll email you a link to confirm from your side, and then an administrator reviews the link. If nobody confirms, nothing is linked.\n\nIf you didn’t ask for this, change your password.`,
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
catch (err) {
|
|
385
|
+
req.payload.logger.warn({ err }, 'Hats: link request note not sent');
|
|
386
|
+
}
|
|
387
|
+
if (!target)
|
|
388
|
+
return;
|
|
389
|
+
try {
|
|
390
|
+
await opts.sendEmail({
|
|
391
|
+
payload: req.payload,
|
|
392
|
+
to: String(target.email),
|
|
393
|
+
subject: 'Confirm linking your accounts',
|
|
394
|
+
text: `Someone signed in as ${labelOf(full)} asked to link that account with ${labelOf(target)}, so one person can switch between them.\n\nIf that was you, confirm here within ${hours} hours:\n${await confirmLink(req, opts, token)}\n\nIf it wasn’t you, ignore this email: nothing is linked without it.`,
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
catch (err) {
|
|
398
|
+
// The invitation never arrived, so its token must never work.
|
|
399
|
+
req.payload.logger.warn({ err }, 'Hats: link invitation not sent');
|
|
400
|
+
await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: { account: null, holds: holdFor(null), tokenHash: null }, overrideAccess: true, req }));
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
// With no set yet, the event waits for confirmation, when the set exists, so `link` is always a real set.
|
|
404
|
+
if (mine)
|
|
405
|
+
await tell(req.payload, req, { type: 'link-requested', req, link: idOf(mine.link), by: me, account: String(target.id) });
|
|
348
406
|
};
|
|
349
|
-
let
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
catch (error) {
|
|
360
|
-
// Someone else linked that account a moment ago (the one-set-per-account index): say the same as always.
|
|
361
|
-
req.payload.logger.warn({ err: error }, 'Hats: link request not recorded');
|
|
362
|
-
return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
|
|
363
|
-
}
|
|
364
|
-
await opts.onEvent?.({ type: 'link-requested', req, link: link, by: me, account: String(target.id) });
|
|
407
|
+
let finished = false;
|
|
408
|
+
const done = work()
|
|
409
|
+
.catch((err) => req.payload.logger.warn({ err }, 'Hats: link request not finished'))
|
|
410
|
+
.finally(() => {
|
|
411
|
+
finished = true;
|
|
412
|
+
});
|
|
413
|
+
trackWork(done);
|
|
414
|
+
await answer;
|
|
415
|
+
if (!finished)
|
|
416
|
+
void done.then(() => req.payload.logger.info('Hats: a link request finished after its answer. Raise linkAnswerMs if this repeats.'));
|
|
365
417
|
return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
|
|
366
418
|
},
|
|
367
419
|
};
|
|
@@ -392,15 +444,123 @@ const confirm = {
|
|
|
392
444
|
const bad = () => page('That link didn’t work', '<p>It may have expired or been used already. Ask again from your account page.</p>', 400);
|
|
393
445
|
if (!token)
|
|
394
446
|
return bad();
|
|
395
|
-
const
|
|
447
|
+
const opts = hatsOptions(req.payload);
|
|
448
|
+
const hash = hashToken(token);
|
|
449
|
+
const thanks = () => page('Confirmed', '<p>Thanks. Once every account in the link is confirmed, an administrator reviews it. You can close this page.</p>');
|
|
450
|
+
// The asker confirming their own side, after the other account confirmed.
|
|
451
|
+
const { docs } = await req.payload.find({ collection: MEMBERS, where: { tokenHash: { equals: hash } }, limit: 1, depth: 0, overrideAccess: true, showHiddenFields: true, pagination: false, req });
|
|
396
452
|
const m = docs[0];
|
|
397
|
-
if (
|
|
453
|
+
if (m) {
|
|
454
|
+
if (m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
|
|
455
|
+
return bad();
|
|
456
|
+
if ((await members(req, idOf(m.link))).length > opts.maxLinked)
|
|
457
|
+
return bad();
|
|
458
|
+
await asPlugin(req, () => req.payload.update({ collection: MEMBERS, id: m.id, data: { status: 'confirmed', confirmedAt: new Date().toISOString(), tokenHash: null, tokenExpires: null }, overrideAccess: true, req }));
|
|
459
|
+
await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: idOf(m.link), account: idOf(m.user) });
|
|
460
|
+
return thanks();
|
|
461
|
+
}
|
|
462
|
+
// The invited account confirming a request. The token works once: the request is deleted before anything else.
|
|
463
|
+
const found = await req.payload.find({ collection: REQUESTS, where: { tokenHash: { equals: hash } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
464
|
+
const r = found.docs[0];
|
|
465
|
+
if (!r || r.account == null || new Date(r.expiresAt).getTime() < Date.now())
|
|
466
|
+
return bad();
|
|
467
|
+
let gone;
|
|
468
|
+
try {
|
|
469
|
+
gone = await asPlugin(req, () => req.payload.delete({ collection: REQUESTS, where: { and: [{ id: { equals: r.id } }, { tokenHash: { equals: hash } }] }, overrideAccess: true, req }));
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
return bad(); // the same token confirmed at the same moment: the other confirmation has it
|
|
473
|
+
}
|
|
474
|
+
if (gone.docs?.length !== 1)
|
|
475
|
+
return bad();
|
|
476
|
+
const by = idOf(r.requestedBy);
|
|
477
|
+
const account = idOf(r.account);
|
|
478
|
+
if (by === account)
|
|
479
|
+
return bad();
|
|
480
|
+
const asker = await loadUser(req, by);
|
|
481
|
+
const invited = await loadUser(req, account);
|
|
482
|
+
if (!asker || !invited || (await membershipOf(req, account)))
|
|
483
|
+
return bad();
|
|
484
|
+
const mine = await membershipOf(req, by);
|
|
485
|
+
const existing = mine ? idOf(mine.link) : null;
|
|
486
|
+
// The invitation was for the asker's set as it was then. A set the asker started since, from another of their own
|
|
487
|
+
// requests, is still theirs; any other change (they joined or left a set) needs a new request.
|
|
488
|
+
const was = r.link ? String(r.link) : null;
|
|
489
|
+
if (existing !== was) {
|
|
490
|
+
const started = was === null && existing ? (await req.payload.findByID({ collection: LINKS, id: existing, depth: 0, overrideAccess: true, disableErrors: true, req })) : null;
|
|
491
|
+
if (!started || idOf(started.requestedBy) !== by)
|
|
492
|
+
return bad();
|
|
493
|
+
}
|
|
494
|
+
if (existing && (await members(req, existing)).length + 1 > opts.maxLinked)
|
|
495
|
+
return bad();
|
|
496
|
+
const made = { rows: [] };
|
|
497
|
+
try {
|
|
498
|
+
await asPlugin(req, async () => {
|
|
499
|
+
const link = existing ?? String((await req.payload.create({ collection: LINKS, data: { requestedBy: relId(req.payload, opts.users, by), label: `Started by ${labelOf(asker)}` }, overrideAccess: true, req })).id);
|
|
500
|
+
if (!existing)
|
|
501
|
+
made.link = link;
|
|
502
|
+
const now = new Date();
|
|
503
|
+
const row = await req.payload.create({
|
|
504
|
+
collection: MEMBERS,
|
|
505
|
+
data: { link: relId(req.payload, LINKS, link), user: relId(req.payload, opts.users, account), status: 'confirmed', confirmedAt: now.toISOString(), addedBy: relId(req.payload, opts.users, by) },
|
|
506
|
+
overrideAccess: true,
|
|
507
|
+
req,
|
|
508
|
+
});
|
|
509
|
+
made.rows.push(String(row.id));
|
|
510
|
+
if (!mine) {
|
|
511
|
+
// The asker confirms from their own email too, now that the other account has said yes.
|
|
512
|
+
const own = newToken();
|
|
513
|
+
const hours = opts.confirmHours;
|
|
514
|
+
const ownRow = await req.payload.create({
|
|
515
|
+
collection: MEMBERS,
|
|
516
|
+
data: { link: relId(req.payload, LINKS, link), user: relId(req.payload, opts.users, by), status: 'requested', tokenHash: hashToken(own), tokenExpires: new Date(now.getTime() + hours * 3_600_000).toISOString(), addedBy: relId(req.payload, opts.users, by) },
|
|
517
|
+
overrideAccess: true,
|
|
518
|
+
req,
|
|
519
|
+
});
|
|
520
|
+
made.rows.push(String(ownRow.id));
|
|
521
|
+
made.own = own;
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
// The site's own callbacks run after the plugin's writes, with its mark off the request.
|
|
525
|
+
if (made.own) {
|
|
526
|
+
const own = made.own;
|
|
527
|
+
const hours = opts.confirmHours;
|
|
528
|
+
await opts.sendEmail({
|
|
529
|
+
payload: req.payload,
|
|
530
|
+
to: String(asker.email),
|
|
531
|
+
subject: 'Confirm linking your accounts',
|
|
532
|
+
text: `${labelOf(invited)} agreed to link with ${labelOf(asker)}, so one person can switch between them.\n\nConfirm from your side here within ${hours} hours:\n${await confirmLink(req, opts, own)}\n\nIf you didn’t ask for this, ignore this email: nothing is linked without it.`,
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
catch (error) {
|
|
537
|
+
// Someone linked one of these accounts a moment ago, or the email didn't go: undo what this made.
|
|
538
|
+
req.payload.logger.warn({ err: error }, 'Hats: link confirmation not recorded');
|
|
539
|
+
await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
|
|
540
|
+
for (const id of made.rows)
|
|
541
|
+
await removeWhere(req.payload, { collection: MEMBERS, where: { id: { equals: id } }, overrideAccess: true, req });
|
|
542
|
+
if (made.link)
|
|
543
|
+
await removeWhere(req.payload, { collection: LINKS, where: { id: { equals: made.link } }, overrideAccess: true, req });
|
|
544
|
+
})).catch((err) => req.payload.logger.warn({ err }, 'Hats: link confirmation clean-up skipped'));
|
|
398
545
|
return bad();
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
546
|
+
}
|
|
547
|
+
// The records are written by now, so a handler that fails can't undo or block them: it's logged and skipped.
|
|
548
|
+
if (made.link)
|
|
549
|
+
await tell(req.payload, req, { type: 'link-requested', req, link: made.link, by, account });
|
|
550
|
+
await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: existing ?? made.link, account });
|
|
551
|
+
return thanks();
|
|
402
552
|
},
|
|
403
553
|
};
|
|
554
|
+
/** Whether `v` is an account id written the one way the users collection writes its ids. */
|
|
555
|
+
function exactId(req, opts, v) {
|
|
556
|
+
if (typeof v !== 'string' && typeof v !== 'number')
|
|
557
|
+
return false;
|
|
558
|
+
const s = String(v);
|
|
559
|
+
const type = req.payload.collections[opts.users]?.customIDType ?? req.payload.db.defaultIDType;
|
|
560
|
+
if (type === 'number')
|
|
561
|
+
return /^(0|-?[1-9]\d{0,15})$/.test(s) && Number.isSafeInteger(Number(s));
|
|
562
|
+
return typeof v === 'string' && s.length > 0 && s.length <= 256 && s.trim() === s;
|
|
563
|
+
}
|
|
404
564
|
/** POST /api/hats/unlink { account? }: take an account (default: the acting one) out of the set. Self-serve, at once. */
|
|
405
565
|
const unlink = {
|
|
406
566
|
path: '/hats/unlink',
|
|
@@ -410,14 +570,21 @@ const unlink = {
|
|
|
410
570
|
const { opts, full, person } = await actor(req);
|
|
411
571
|
await blockedReason(req, opts);
|
|
412
572
|
const me = String(full.id);
|
|
413
|
-
const
|
|
573
|
+
const asked = req.data?.account ?? me;
|
|
574
|
+
const notInSet = () => refuse('That account isn’t in your linked set.', 404, 'notInSet');
|
|
575
|
+
// Only an id exactly as the account has it: no other spelling of a number, and nothing the database would have to
|
|
576
|
+
// make sense of first.
|
|
577
|
+
if (!exactId(req, opts, asked))
|
|
578
|
+
notInSet();
|
|
579
|
+
const account = String(asked);
|
|
414
580
|
const mine = await membershipOf(req, me);
|
|
415
581
|
const theirs = account === me ? mine : await membershipOf(req, account);
|
|
416
|
-
|
|
417
|
-
|
|
582
|
+
// Another account still waiting to confirm is hidden from the set, so it answers as if it weren't there.
|
|
583
|
+
if (!mine || !theirs || idOf(theirs.user) !== account || idOf(mine.link) !== idOf(theirs.link) || (account !== me && theirs.status === 'requested'))
|
|
584
|
+
notInSet();
|
|
418
585
|
const link = idOf(theirs.link);
|
|
419
586
|
await asPlugin(req, () => req.payload.delete({ collection: MEMBERS, id: theirs.id, overrideAccess: true, req }));
|
|
420
|
-
await
|
|
587
|
+
await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: me });
|
|
421
588
|
// If this session was switched in through the account just removed, it ended with the unlink.
|
|
422
589
|
return json({ ok: true, signedOut: account === me ? person !== me : person === account });
|
|
423
590
|
},
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type SwitchInput, type SwitchResult } from './endpoints.js';
|
|
|
3
3
|
import { type HatsOptions } from './types.js';
|
|
4
4
|
export { hatsStateOf } from './state.js';
|
|
5
5
|
export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
|
|
6
|
-
export { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
6
|
+
export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
7
7
|
export type { SwitchInput, SwitchResult };
|
|
8
8
|
/**
|
|
9
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
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { hatCollections } from './collections.js';
|
|
2
2
|
import { hatEndpoints, runSwitch } from './endpoints.js';
|
|
3
3
|
import { revokeSessions, wrapStrategies } from './sessions.js';
|
|
4
|
-
import { asPlugin } from './state.js';
|
|
5
|
-
import { MEMBERS, SESSIONS } from './types.js';
|
|
4
|
+
import { asPlugin, changeWhere, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks } from './state.js';
|
|
5
|
+
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
6
6
|
export { hatsStateOf } from './state.js';
|
|
7
7
|
export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
|
|
8
|
-
export { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
8
|
+
export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
9
9
|
/**
|
|
10
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
11
|
* `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
|
|
@@ -27,6 +27,7 @@ export const hats = (options) => (config) => {
|
|
|
27
27
|
users: 'users',
|
|
28
28
|
maxLinked: 4,
|
|
29
29
|
confirmHours: 24,
|
|
30
|
+
linkAnswerMs: 2000,
|
|
30
31
|
showSwitch: undefined,
|
|
31
32
|
adminSwitch: true,
|
|
32
33
|
sendEmail: ({ payload, to, subject, text }) => payload.sendEmail({ to, subject, text }),
|
|
@@ -34,33 +35,61 @@ export const hats = (options) => (config) => {
|
|
|
34
35
|
};
|
|
35
36
|
if (opts.maxLinked < 2)
|
|
36
37
|
throw new Error('hats: maxLinked must be at least 2.');
|
|
38
|
+
if (typeof opts.linkAnswerMs !== 'number' || !Number.isFinite(opts.linkAnswerMs) || opts.linkAnswerMs < 0 || opts.linkAnswerMs > 2_147_483_647)
|
|
39
|
+
throw new Error('hats: linkAnswerMs must be a number of milliseconds, from 0 to 2147483647.');
|
|
37
40
|
const users = (config.collections ?? []).find((c) => c.slug === opts.users);
|
|
38
41
|
if (!users?.auth)
|
|
39
42
|
throw new Error(`hats: no auth collection "${opts.users}".`);
|
|
40
43
|
if (typeof users.auth === 'object' && users.auth.useSessions === false)
|
|
41
44
|
throw new Error('hats: needs Payload sessions; remove auth.useSessions: false.');
|
|
42
|
-
for (const slug of ['hat-links', MEMBERS, SESSIONS])
|
|
45
|
+
for (const slug of ['hat-links', MEMBERS, SESSIONS, REQUESTS])
|
|
43
46
|
if ((config.collections ?? []).some((c) => c.slug === slug))
|
|
44
47
|
throw new Error(`hats: a collection "${slug}" already exists.`);
|
|
48
|
+
// MongoDB keeps 0.4.0's schema and indexes exactly; only SQL adapters (every other adapter Payload ships) get the
|
|
49
|
+
// nullable account columns their foreign keys need.
|
|
50
|
+
const sql = config.db?.name !== 'mongoose';
|
|
45
51
|
const ids = (u) => new Set(opts.hatsOf(u).map((h) => h.id));
|
|
46
52
|
// Losing a hat ends every session switched into the account: it comes back in through the switch, re-checked.
|
|
47
|
-
const afterChange = async ({ doc, previousDoc, operation, req }) => {
|
|
53
|
+
const afterChange = ownHook(async ({ doc, previousDoc, operation, req }) => {
|
|
48
54
|
if (operation !== 'update' || !previousDoc)
|
|
49
55
|
return doc;
|
|
50
56
|
const now = ids(doc);
|
|
51
57
|
if ([...ids(previousDoc)].some((h) => !now.has(h)))
|
|
52
58
|
await revokeSessions(req.payload, { and: [{ user: { equals: String(doc.id) } }, { via: { exists: true } }, { via: { not_equals: null } }] }, 'lost a role', req);
|
|
53
59
|
return doc;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
+
});
|
|
61
|
+
// Once an account is deleted, nothing of the plugin's points at it. This runs in afterDelete, so only for a delete
|
|
62
|
+
// that happened: one refused or failed before it (a site hook, access, one document of a bulk delete) changes
|
|
63
|
+
// nothing here. It runs before the site's own afterDelete hooks, inside the delete's transaction where there is
|
|
64
|
+
// one. On SQL databases the foreign keys have already set these columns to null, so null rows go too. Payload runs
|
|
65
|
+
// a bulk delete's documents side by side; `serial` runs this one account at a time. Any database failure in here
|
|
66
|
+
// throws, so the delete fails with it: with a transaction the whole delete is undone, and without one the caller
|
|
67
|
+
// still gets the error (a switched session through the deleted account is refused anyway, see `applyHat`).
|
|
68
|
+
const afterDelete = ownHook(async ({ id, req }) => {
|
|
69
|
+
const p = req.payload;
|
|
70
|
+
const me = relId(p, opts.users, id);
|
|
71
|
+
const mineOrGone = (field) => ({ or: [{ [field]: { equals: me } }, { [field]: { exists: false } }] });
|
|
72
|
+
await serial(req, () => asPlugin(req, async () => {
|
|
73
|
+
// One row at a time, so each leaving takes its set's members as they are at that moment.
|
|
74
|
+
const rows = await p.find({ collection: MEMBERS, where: mineOrGone('user'), limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
|
|
75
|
+
for (const r of rows.docs)
|
|
76
|
+
await removeWhere(p, { collection: MEMBERS, where: { id: { equals: r.id } }, overrideAccess: true, req });
|
|
77
|
+
await removeWhere(p, { collection: REQUESTS, where: mineOrGone('requestedBy'), overrideAccess: true, req });
|
|
78
|
+
// Requests to the account stay, emptied, until they expire: they still count toward the asker's limit, so
|
|
79
|
+
// deleting an account frees nothing the asker could notice. At most one request holds the account.
|
|
80
|
+
await changeWhere(p, { collection: REQUESTS, where: { or: [{ account: { equals: me } }, { holds: { equals: `account:${String(id)}` } }] }, data: { account: null, holds: `none:${newToken()}`, tokenHash: null }, overrideAccess: true, req });
|
|
81
|
+
// Who started a set, added or approved an account: cleared, along with the set's label, which names them.
|
|
82
|
+
await changeWhere(p, { collection: LINKS, where: mineOrGone('requestedBy'), data: { requestedBy: null, label: 'Started by a deleted account' }, overrideAccess: true, req });
|
|
83
|
+
for (const field of ['addedBy', 'approvedBy'])
|
|
84
|
+
await changeWhere(p, { collection: MEMBERS, where: { and: [{ [field]: { equals: me } }, { user: { exists: true } }] }, data: { [field]: null }, overrideAccess: true, req });
|
|
85
|
+
}));
|
|
86
|
+
await revokeSessions(p, { or: [{ user: { equals: String(id) } }, { via: { equals: String(id) } }] }, 'account deleted', req);
|
|
87
|
+
});
|
|
88
|
+
const afterLogout = ownHook(async ({ req }) => {
|
|
60
89
|
const sid = req.user?._sid;
|
|
61
90
|
if (sid)
|
|
62
|
-
await req.payload
|
|
63
|
-
};
|
|
91
|
+
await changeWhere(req.payload, { collection: SESSIONS, where: { sid: { equals: sid } }, data: { revokedAt: new Date().toISOString() }, overrideAccess: true, req });
|
|
92
|
+
});
|
|
64
93
|
const onInit = config.onInit;
|
|
65
94
|
return {
|
|
66
95
|
...config,
|
|
@@ -71,12 +100,12 @@ export const hats = (options) => (config) => {
|
|
|
71
100
|
hooks: {
|
|
72
101
|
...c.hooks,
|
|
73
102
|
afterChange: [...(c.hooks?.afterChange ?? []), afterChange],
|
|
74
|
-
afterDelete: [...(c.hooks?.afterDelete ?? [])
|
|
103
|
+
afterDelete: [afterDelete, ...(c.hooks?.afterDelete ?? [])],
|
|
75
104
|
afterLogout: [...(c.hooks?.afterLogout ?? []), afterLogout],
|
|
76
105
|
},
|
|
77
106
|
}
|
|
78
107
|
: c),
|
|
79
|
-
...hatCollections(opts),
|
|
108
|
+
...hatCollections(opts, sql),
|
|
80
109
|
],
|
|
81
110
|
endpoints: [...(config.endpoints ?? []), ...hatEndpoints],
|
|
82
111
|
admin: opts.adminSwitch === false
|
|
@@ -84,6 +113,7 @@ export const hats = (options) => (config) => {
|
|
|
84
113
|
: { ...config.admin, components: { ...config.admin?.components, actions: [...(config.admin?.components?.actions ?? []), '@extantape/payload-plugin-hats/client#HatSwitcher'] } },
|
|
85
114
|
custom: { ...config.custom, hats: opts },
|
|
86
115
|
onInit: async (payload) => {
|
|
116
|
+
unmarkForeignHooks(payload);
|
|
87
117
|
await onInit?.(payload);
|
|
88
118
|
wrapStrategies(payload, opts);
|
|
89
119
|
},
|
package/dist/sessions.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { asPlugin, attachState, hatsOptions, idOf } from './state.js';
|
|
1
|
+
import { asPlugin, attachState, DISSOLVING, hatsOptions, idOf, relId, removeWhere, tell, withMark } from './state.js';
|
|
2
2
|
import { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
3
3
|
export async function sessionBySid(payload, sid, req) {
|
|
4
4
|
const { docs } = await payload.find({ collection: SESSIONS, where: { sid: { equals: sid } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
@@ -29,8 +29,10 @@ export async function revokeSessions(payload, where, reason, req) {
|
|
|
29
29
|
await revokeSid(payload, s.user, s.sid, req);
|
|
30
30
|
await tombstone(payload, s.id, req);
|
|
31
31
|
}
|
|
32
|
+
// This can run inside the plugin's own writes (an unlink, a set dissolving, an account deleted), so the site's
|
|
33
|
+
// handler runs unmarked, and one that fails or hangs can't block or undo them.
|
|
32
34
|
if (docs.length)
|
|
33
|
-
await
|
|
35
|
+
await tell(payload, req, { type: 'sessions-revoked', payload, sessions: docs.length, reason });
|
|
34
36
|
return docs.length;
|
|
35
37
|
}
|
|
36
38
|
/** A set with one account left isn't a link any more: remove it. */
|
|
@@ -38,18 +40,13 @@ export async function dissolveIfAlone(payload, link, req) {
|
|
|
38
40
|
const { docs } = await payload.find({ collection: MEMBERS, where: { link: { equals: link } }, limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
|
|
39
41
|
if (docs.length > 1)
|
|
40
42
|
return;
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
finally {
|
|
51
|
-
req.context.hatsDissolving = before;
|
|
52
|
-
}
|
|
43
|
+
await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
|
|
44
|
+
// By id one at a time, and gone already is fine: an account's clean-up may have removed a row a moment ago. A
|
|
45
|
+
// row that fails to go throws, so the unlink or delete that set this off fails too, and isn't reported as done.
|
|
46
|
+
for (const d of docs)
|
|
47
|
+
await removeWhere(payload, { collection: MEMBERS, where: { id: { equals: d.id } }, overrideAccess: true, req });
|
|
48
|
+
await removeWhere(payload, { collection: LINKS, where: { id: { equals: link } }, overrideAccess: true, req });
|
|
49
|
+
}));
|
|
53
50
|
await revokeSessions(payload, { link: { equals: link } }, 'set dissolved', req);
|
|
54
51
|
}
|
|
55
52
|
/** The approved set two accounts are both in, or null. Read fresh every time. */
|
|
@@ -63,10 +60,13 @@ export async function sharedLink(payload, a, b, req) {
|
|
|
63
60
|
pagination: false,
|
|
64
61
|
req,
|
|
65
62
|
});
|
|
66
|
-
|
|
63
|
+
// Only rows for exactly these two accounts count (on MongoDB a query for the text "null" can match a row whose
|
|
64
|
+
// account was cleared).
|
|
65
|
+
const rows = docs.filter((d) => d.user != null && (idOf(d.user) === a || idOf(d.user) === b));
|
|
66
|
+
const [x, y] = rows;
|
|
67
67
|
if (a === b)
|
|
68
68
|
return x ? idOf(x.link) : null;
|
|
69
|
-
return x && y && idOf(x.link) === idOf(y.link) ? idOf(x.link) : null;
|
|
69
|
+
return x && y && idOf(x.user) !== idOf(y.user) && idOf(x.link) === idOf(y.link) ? idOf(x.link) : null;
|
|
70
70
|
}
|
|
71
71
|
/** The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest. */
|
|
72
72
|
export function wornHat(hats, s) {
|
|
@@ -93,6 +93,13 @@ export async function applyHat(payload, opts, user) {
|
|
|
93
93
|
return null;
|
|
94
94
|
}
|
|
95
95
|
if (s?.via) {
|
|
96
|
+
// The account this session was switched in through must still exist. If its delete failed partway (a database
|
|
97
|
+
// error without a transaction), its member row can outlive it: the session is refused all the same.
|
|
98
|
+
const there = await payload.db.count({ collection: opts.users, where: { id: { equals: relId(payload, opts.users, s.via) } } });
|
|
99
|
+
if (!there?.totalDocs) {
|
|
100
|
+
await revokeSessions(payload, { sid: { equals: sid } }, 'account deleted');
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
96
103
|
const link = await sharedLink(payload, String(user.id), String(s.via));
|
|
97
104
|
if (!link || link !== String(s.link)) {
|
|
98
105
|
await revokeSessions(payload, { sid: { equals: sid } }, 'no longer linked');
|
package/dist/state.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Payload, PayloadRequest } from 'payload';
|
|
2
|
-
import type { HatsState, HatsUser, ResolvedHatsOptions } from './types.js';
|
|
1
|
+
import type { Payload, PayloadRequest, Where } from 'payload';
|
|
2
|
+
import type { HatsEvent, HatsState, HatsUser, ResolvedHatsOptions } from './types.js';
|
|
3
3
|
/** Attaches the session's hat state to a user without it ever being serialised into a response. */
|
|
4
4
|
export declare function attachState<T extends object>(user: T, state: HatsState): T;
|
|
5
5
|
/** The hat state of a signed-in user (or request), for audit logs and the site's own checks. */
|
|
@@ -7,7 +7,71 @@ export declare function hatsStateOf(userOrReq: unknown): HatsState | null;
|
|
|
7
7
|
export declare const hatsOptions: (payload: Payload) => ResolvedHatsOptions;
|
|
8
8
|
export declare const newToken: () => string;
|
|
9
9
|
export declare const hashToken: (token: string) => string;
|
|
10
|
-
/**
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* The marks the plugin puts on its own writes. They live in an async context only this module holds, so code outside
|
|
12
|
+
* the plugin can't set them: nothing in `context` (which any server code can pass) counts. A mark is set for one
|
|
13
|
+
* request object and holds for the code `withMark` runs and everything that code awaits, Payload's hooks included
|
|
14
|
+
* (the Local API keeps the same request object through nested calls and hooks when `req` is passed, which every
|
|
15
|
+
* plugin write does). It ends when that code returns, and code started elsewhere, or by the site from inside it
|
|
16
|
+
* through `unmarked`, never sees it. (Symbol keys on `context` don't work: Payload treats a context with only symbol
|
|
17
|
+
* keys as empty.)
|
|
18
|
+
*/
|
|
19
|
+
export declare const INTERNAL: unique symbol;
|
|
20
|
+
export declare const DISSOLVING: unique symbol;
|
|
21
|
+
type Mark = typeof INTERNAL | typeof DISSOLVING;
|
|
22
|
+
export declare const isInternal: (req: PayloadRequest) => boolean;
|
|
23
|
+
export declare const isDissolving: (req: PayloadRequest) => boolean;
|
|
24
|
+
/** Runs `fn` with the request carrying `mark`. The mark holds only inside `fn`, however it is nested or run alongside. */
|
|
25
|
+
export declare function withMark<T>(req: PayloadRequest, mark: Mark, fn: () => Promise<T>): Promise<T>;
|
|
26
|
+
/** Runs `fn` with the request marked as the plugin's own. */
|
|
27
|
+
export declare const asPlugin: <T>(req: PayloadRequest, fn: () => Promise<T>) => Promise<T>;
|
|
28
|
+
export declare const ownHook: <T extends (...args: never[]) => unknown>(fn: T) => T;
|
|
29
|
+
/** Wraps every hook that isn't the plugin's, in every collection, global and the config, to run with the marks off. */
|
|
30
|
+
export declare function unmarkForeignHooks(payload: Payload): void;
|
|
31
|
+
/**
|
|
32
|
+
* A bulk delete or update by `where` that throws when any row fails. Payload's bulk operations catch a row's error and
|
|
33
|
+
* return it in `errors`; with a transaction, the failure has usually ended the transaction already, so carrying on
|
|
34
|
+
* would report a change that was undone. The plugin's own bulk writes go through these.
|
|
35
|
+
*/
|
|
36
|
+
type ByWhere = {
|
|
37
|
+
collection: unknown;
|
|
38
|
+
where: Where;
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
};
|
|
41
|
+
export declare function removeWhere(payload: Payload, args: ByWhere): Promise<{
|
|
42
|
+
docs: unknown[];
|
|
43
|
+
errors?: unknown[];
|
|
44
|
+
}>;
|
|
45
|
+
export declare function changeWhere(payload: Payload, args: ByWhere & {
|
|
46
|
+
data: unknown;
|
|
47
|
+
}): Promise<{
|
|
48
|
+
docs: unknown[];
|
|
49
|
+
errors?: unknown[];
|
|
50
|
+
}>;
|
|
51
|
+
/**
|
|
52
|
+
* An id as a relationship to `slug` stores it: a number where that collection's ids are numbers (SQL adapters by
|
|
53
|
+
* default, or a custom number id), otherwise as it is. The plugin compares ids as strings, so every id it writes
|
|
54
|
+
* into a relationship goes through this first.
|
|
55
|
+
*/
|
|
56
|
+
export declare function relId(payload: Payload, slug: string, v: unknown): string | number | null;
|
|
57
|
+
/**
|
|
58
|
+
* Runs one of the site's own callbacks with the plugin's marks off the request, so nothing the site does from it
|
|
59
|
+
* passes as the plugin. The marks come back afterwards.
|
|
60
|
+
*/
|
|
61
|
+
export declare function unmarked<T>(req: PayloadRequest | undefined, fn: () => T | Promise<T>): Promise<T>;
|
|
62
|
+
export declare function serial<T>(req: PayloadRequest, fn: () => Promise<T>): Promise<T>;
|
|
63
|
+
/** The longest the plugin waits for the site's `onEvent` handler; it carries on unwaited after. */
|
|
64
|
+
export declare const TELL_MS = 2000;
|
|
65
|
+
/** An error's name for the log, only when it's a short plain word; anything else, or a name that throws, is `Error`. */
|
|
66
|
+
export declare function safeName(error: unknown): string;
|
|
67
|
+
/**
|
|
68
|
+
* Tells the site about an event once the change is made. The handler runs unmarked. One that throws is logged by its
|
|
69
|
+
* error's name only (a message can carry what the event was about) and skipped, and one still running after
|
|
70
|
+
* `TELL_MS` is left to finish unwaited, so a handler can never block or undo what already happened.
|
|
71
|
+
*/
|
|
72
|
+
export declare function tell(payload: Payload, req: PayloadRequest | undefined, event: HatsEvent): Promise<void>;
|
|
73
|
+
export declare function trackWork(p: Promise<unknown>): void;
|
|
74
|
+
/** Resolves once every link request's work has finished, including any started meanwhile. */
|
|
75
|
+
export declare function linkWorkSettled(): Promise<void>;
|
|
12
76
|
export declare const idOf: (v: unknown) => string;
|
|
13
77
|
export type { HatsUser };
|
package/dist/state.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
1
2
|
import { createHash, randomBytes } from 'node:crypto';
|
|
2
3
|
const KEY = '_hats';
|
|
3
4
|
/** Attaches the session's hat state to a user without it ever being serialised into a response. */
|
|
@@ -15,15 +16,173 @@ export function hatsStateOf(userOrReq) {
|
|
|
15
16
|
export const hatsOptions = (payload) => payload.config.custom?.hats;
|
|
16
17
|
export const newToken = () => randomBytes(32).toString('base64url');
|
|
17
18
|
export const hashToken = (token) => createHash('sha256').update(`hats:${token}`).digest('hex');
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
/**
|
|
20
|
+
* The marks the plugin puts on its own writes. They live in an async context only this module holds, so code outside
|
|
21
|
+
* the plugin can't set them: nothing in `context` (which any server code can pass) counts. A mark is set for one
|
|
22
|
+
* request object and holds for the code `withMark` runs and everything that code awaits, Payload's hooks included
|
|
23
|
+
* (the Local API keeps the same request object through nested calls and hooks when `req` is passed, which every
|
|
24
|
+
* plugin write does). It ends when that code returns, and code started elsewhere, or by the site from inside it
|
|
25
|
+
* through `unmarked`, never sees it. (Symbol keys on `context` don't work: Payload treats a context with only symbol
|
|
26
|
+
* keys as empty.)
|
|
27
|
+
*/
|
|
28
|
+
export const INTERNAL = Symbol('hats: the plugin itself');
|
|
29
|
+
export const DISSOLVING = Symbol('hats: dissolving a set');
|
|
30
|
+
const marks = new AsyncLocalStorage();
|
|
31
|
+
const has = (req, mark) => Boolean(req && marks.getStore()?.get(req)?.has(mark));
|
|
32
|
+
export const isInternal = (req) => has(req, INTERNAL);
|
|
33
|
+
export const isDissolving = (req) => has(req, DISSOLVING);
|
|
34
|
+
/** Runs `fn` with the request carrying `mark`. The mark holds only inside `fn`, however it is nested or run alongside. */
|
|
35
|
+
export async function withMark(req, mark, fn) {
|
|
36
|
+
const now = new Map(marks.getStore() ?? []);
|
|
37
|
+
now.set(req, new Set([...(now.get(req) ?? []), mark]));
|
|
38
|
+
return await marks.run(now, fn);
|
|
39
|
+
}
|
|
40
|
+
/** Runs `fn` with the request marked as the plugin's own. */
|
|
41
|
+
export const asPlugin = (req, fn) => withMark(req, INTERNAL, fn);
|
|
42
|
+
/**
|
|
43
|
+
* Hooks the plugin owns. Every other hook (the site's, another plugin's), on any collection, runs with the marks
|
|
44
|
+
* off, so code that isn't the plugin's never acts as the plugin, even when a plugin write sets it off on the same
|
|
45
|
+
* request (an afterDelete another plugin put on `hat-members`, say).
|
|
46
|
+
*/
|
|
47
|
+
const own = new WeakSet();
|
|
48
|
+
const plain = new WeakSet();
|
|
49
|
+
export const ownHook = (fn) => {
|
|
50
|
+
own.add(fn);
|
|
51
|
+
return fn;
|
|
52
|
+
};
|
|
53
|
+
function unmarkHook(fn) {
|
|
54
|
+
if (typeof fn !== 'function' || own.has(fn) || plain.has(fn))
|
|
55
|
+
return fn;
|
|
56
|
+
const wrapped = (...args) => marks.exit(() => fn(...args));
|
|
57
|
+
plain.add(wrapped);
|
|
58
|
+
return wrapped;
|
|
59
|
+
}
|
|
60
|
+
function unmarkHookLists(hooks) {
|
|
61
|
+
if (!hooks || typeof hooks !== 'object')
|
|
62
|
+
return;
|
|
63
|
+
const lists = hooks;
|
|
64
|
+
for (const key of Object.keys(lists))
|
|
65
|
+
if (Array.isArray(lists[key]))
|
|
66
|
+
lists[key] = lists[key].map(unmarkHook);
|
|
67
|
+
}
|
|
68
|
+
function unmarkFieldHooks(fields) {
|
|
69
|
+
if (!Array.isArray(fields))
|
|
70
|
+
return;
|
|
71
|
+
for (const f of fields) {
|
|
72
|
+
if (!f || typeof f !== 'object')
|
|
73
|
+
continue;
|
|
74
|
+
unmarkHookLists(f.hooks);
|
|
75
|
+
unmarkFieldHooks(f.fields);
|
|
76
|
+
for (const b of (Array.isArray(f.blocks) ? f.blocks : []))
|
|
77
|
+
unmarkFieldHooks(b?.fields);
|
|
78
|
+
for (const t of (Array.isArray(f.tabs) ? f.tabs : []))
|
|
79
|
+
unmarkFieldHooks(t?.fields);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Wraps every hook that isn't the plugin's, in every collection, global and the config, to run with the marks off. */
|
|
83
|
+
export function unmarkForeignHooks(payload) {
|
|
84
|
+
unmarkHookLists(payload.config.hooks);
|
|
85
|
+
const configs = [...payload.config.collections, ...(payload.config.globals ?? [])];
|
|
86
|
+
for (const c of configs) {
|
|
87
|
+
unmarkHookLists(c.hooks);
|
|
88
|
+
unmarkFieldHooks(c.fields);
|
|
89
|
+
unmarkFieldHooks(c.flattenedFields);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export async function removeWhere(payload, args) {
|
|
93
|
+
const result = (await payload.delete(args));
|
|
94
|
+
if (result.errors?.length)
|
|
95
|
+
throw new Error(`Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be removed.`);
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
export async function changeWhere(payload, args) {
|
|
99
|
+
const result = (await payload.update(args));
|
|
100
|
+
if (result.errors?.length)
|
|
101
|
+
throw new Error(`Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be changed.`);
|
|
102
|
+
return result;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* An id as a relationship to `slug` stores it: a number where that collection's ids are numbers (SQL adapters by
|
|
106
|
+
* default, or a custom number id), otherwise as it is. The plugin compares ids as strings, so every id it writes
|
|
107
|
+
* into a relationship goes through this first.
|
|
108
|
+
*/
|
|
109
|
+
export function relId(payload, slug, v) {
|
|
110
|
+
if (v == null)
|
|
111
|
+
return null;
|
|
112
|
+
const id = idOf(v);
|
|
113
|
+
const type = payload.collections[slug]?.customIDType ?? payload.db.defaultIDType;
|
|
114
|
+
return type === 'number' && /^-?\d+(\.\d+)?$/.test(id) ? Number(id) : id;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Runs one of the site's own callbacks with the plugin's marks off the request, so nothing the site does from it
|
|
118
|
+
* passes as the plugin. The marks come back afterwards.
|
|
119
|
+
*/
|
|
120
|
+
export async function unmarked(req, fn) {
|
|
121
|
+
const held = marks.getStore();
|
|
122
|
+
if (!req || !held?.has(req))
|
|
23
123
|
return await fn();
|
|
124
|
+
const now = new Map(held);
|
|
125
|
+
now.delete(req);
|
|
126
|
+
return await marks.run(now, fn);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Runs `fn` after every earlier `serial` call on the same request has finished. Payload deletes the documents of a
|
|
130
|
+
* bulk delete side by side on one request; the plugin's clean-up after each account runs one at a time, so two
|
|
131
|
+
* accounts leaving one set together can't each see the other still there.
|
|
132
|
+
*/
|
|
133
|
+
const queues = new WeakMap();
|
|
134
|
+
export function serial(req, fn) {
|
|
135
|
+
const before = queues.get(req) ?? Promise.resolve();
|
|
136
|
+
const run = before.then(fn, fn);
|
|
137
|
+
queues.set(req, run.catch(() => undefined));
|
|
138
|
+
return run;
|
|
139
|
+
}
|
|
140
|
+
/** The longest the plugin waits for the site's `onEvent` handler; it carries on unwaited after. */
|
|
141
|
+
export const TELL_MS = 2000;
|
|
142
|
+
/** An error's name for the log, only when it's a short plain word; anything else, or a name that throws, is `Error`. */
|
|
143
|
+
export function safeName(error) {
|
|
144
|
+
try {
|
|
145
|
+
const name = error?.name;
|
|
146
|
+
return typeof name === 'string' && /^[A-Za-z][A-Za-z0-9_]{0,39}$/.test(name) ? name : typeof error === 'object' && error ? 'Error' : typeof error;
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return 'Error';
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Tells the site about an event once the change is made. The handler runs unmarked. One that throws is logged by its
|
|
154
|
+
* error's name only (a message can carry what the event was about) and skipped, and one still running after
|
|
155
|
+
* `TELL_MS` is left to finish unwaited, so a handler can never block or undo what already happened.
|
|
156
|
+
*/
|
|
157
|
+
export async function tell(payload, req, event) {
|
|
158
|
+
const onEvent = hatsOptions(payload).onEvent;
|
|
159
|
+
if (!onEvent)
|
|
160
|
+
return;
|
|
161
|
+
let timer;
|
|
162
|
+
const late = new Promise((resolve) => {
|
|
163
|
+
timer = setTimeout(() => resolve('late'), TELL_MS);
|
|
164
|
+
});
|
|
165
|
+
const run = unmarked(req, () => onEvent(event)).then(() => 'ok', (error) => {
|
|
166
|
+
payload.logger.error({ msg: `Hats: an onEvent handler failed on ${event.type} (${safeName(error)})` });
|
|
167
|
+
return 'failed';
|
|
168
|
+
});
|
|
169
|
+
try {
|
|
170
|
+
if ((await Promise.race([run, late])) === 'late')
|
|
171
|
+
payload.logger.warn({ msg: `Hats: an onEvent handler on ${event.type} is still running; the plugin didn't wait for it` });
|
|
24
172
|
}
|
|
25
173
|
finally {
|
|
26
|
-
|
|
174
|
+
clearTimeout(timer);
|
|
27
175
|
}
|
|
28
176
|
}
|
|
177
|
+
/** Link requests still working after their answer, so tests (and a graceful shutdown) can wait for them. */
|
|
178
|
+
const working = new Set();
|
|
179
|
+
export function trackWork(p) {
|
|
180
|
+
working.add(p);
|
|
181
|
+
void p.finally(() => working.delete(p));
|
|
182
|
+
}
|
|
183
|
+
/** Resolves once every link request's work has finished, including any started meanwhile. */
|
|
184
|
+
export async function linkWorkSettled() {
|
|
185
|
+
while (working.size)
|
|
186
|
+
await Promise.allSettled([...working]);
|
|
187
|
+
}
|
|
29
188
|
export const idOf = (v) => String(v && typeof v === 'object' && 'id' in v ? v.id : v);
|
package/dist/types.d.ts
CHANGED
|
@@ -131,10 +131,17 @@ export type HatsOptions = {
|
|
|
131
131
|
adminSwitch?: boolean;
|
|
132
132
|
/** Hours a confirmation link works. Default 24. */
|
|
133
133
|
confirmHours?: number;
|
|
134
|
+
/**
|
|
135
|
+
* How long a link request takes to answer, in milliseconds, whatever the address. The records and emails for a
|
|
136
|
+
* request run within this time, so the answer arrives at the same moment whether or not the address has an
|
|
137
|
+
* account. Work still running when it's up carries on after the answer, and is logged. Keep it above your slowest
|
|
138
|
+
* email send, especially on hosts that stop work once a response is sent. Default 2000.
|
|
139
|
+
*/
|
|
140
|
+
linkAnswerMs?: number;
|
|
134
141
|
};
|
|
135
142
|
export type HatsEvent = {
|
|
136
143
|
type: 'link-requested';
|
|
137
|
-
req: PayloadRequest;
|
|
144
|
+
req: PayloadRequest; /** The asker's set. When the asker had none, this fires as the set is made, just before `link-confirmed`, and `req` is the confirming request. */
|
|
138
145
|
link: string;
|
|
139
146
|
by: string;
|
|
140
147
|
account: string;
|
|
@@ -173,3 +180,4 @@ export type ResolvedHatsOptions = Required<Omit<HatsOptions, 'stepUp' | 'stepUpW
|
|
|
173
180
|
export declare const LINKS = "hat-links";
|
|
174
181
|
export declare const MEMBERS = "hat-members";
|
|
175
182
|
export declare const SESSIONS = "hat-sessions";
|
|
183
|
+
export declare const REQUESTS = "hat-requests";
|
package/dist/types.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-hats",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.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",
|