@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/dist/index.js
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import { hatCollections } from './collections.js';
|
|
2
|
-
import { hatEndpoints } from './endpoints.js';
|
|
2
|
+
import { hatEndpoints, runSwitch } from './endpoints.js';
|
|
3
3
|
import { revokeSessions, wrapStrategies } from './sessions.js';
|
|
4
|
-
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
|
+
/**
|
|
10
|
+
* Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
|
|
11
|
+
* `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
|
|
12
|
+
* the old session's revoke), and has no option that skips one. It acts only for `req.user`: with nobody signed in it
|
|
13
|
+
* is refused (`signIn`, 401). It never throws for a refusal. An error from a site hook is a refusal too.
|
|
14
|
+
*
|
|
15
|
+
* On `{ ok: true }` the route must send `cookie` back as `Set-Cookie`. Call it only from a same-origin POST, never
|
|
16
|
+
* from a GET: a GET can be started by a link on another site, and `SameSite=Lax` still sends the sign-in cookie on it.
|
|
17
|
+
*/
|
|
18
|
+
export const switchSession = (req, input) => runSwitch(req, input);
|
|
9
19
|
/**
|
|
10
20
|
* Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
|
|
11
21
|
* holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
|
|
@@ -17,6 +27,7 @@ export const hats = (options) => (config) => {
|
|
|
17
27
|
users: 'users',
|
|
18
28
|
maxLinked: 4,
|
|
19
29
|
confirmHours: 24,
|
|
30
|
+
linkAnswerMs: 2000,
|
|
20
31
|
showSwitch: undefined,
|
|
21
32
|
adminSwitch: true,
|
|
22
33
|
sendEmail: ({ payload, to, subject, text }) => payload.sendEmail({ to, subject, text }),
|
|
@@ -24,33 +35,61 @@ export const hats = (options) => (config) => {
|
|
|
24
35
|
};
|
|
25
36
|
if (opts.maxLinked < 2)
|
|
26
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.');
|
|
27
40
|
const users = (config.collections ?? []).find((c) => c.slug === opts.users);
|
|
28
41
|
if (!users?.auth)
|
|
29
42
|
throw new Error(`hats: no auth collection "${opts.users}".`);
|
|
30
43
|
if (typeof users.auth === 'object' && users.auth.useSessions === false)
|
|
31
44
|
throw new Error('hats: needs Payload sessions; remove auth.useSessions: false.');
|
|
32
|
-
for (const slug of ['hat-links', MEMBERS, SESSIONS])
|
|
45
|
+
for (const slug of ['hat-links', MEMBERS, SESSIONS, REQUESTS])
|
|
33
46
|
if ((config.collections ?? []).some((c) => c.slug === slug))
|
|
34
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';
|
|
35
51
|
const ids = (u) => new Set(opts.hatsOf(u).map((h) => h.id));
|
|
36
52
|
// Losing a hat ends every session switched into the account: it comes back in through the switch, re-checked.
|
|
37
|
-
const afterChange = async ({ doc, previousDoc, operation, req }) => {
|
|
53
|
+
const afterChange = ownHook(async ({ doc, previousDoc, operation, req }) => {
|
|
38
54
|
if (operation !== 'update' || !previousDoc)
|
|
39
55
|
return doc;
|
|
40
56
|
const now = ids(doc);
|
|
41
57
|
if ([...ids(previousDoc)].some((h) => !now.has(h)))
|
|
42
58
|
await revokeSessions(req.payload, { and: [{ user: { equals: String(doc.id) } }, { via: { exists: true } }, { via: { not_equals: null } }] }, 'lost a role', req);
|
|
43
59
|
return doc;
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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 }) => {
|
|
50
89
|
const sid = req.user?._sid;
|
|
51
90
|
if (sid)
|
|
52
|
-
await req.payload
|
|
53
|
-
};
|
|
91
|
+
await changeWhere(req.payload, { collection: SESSIONS, where: { sid: { equals: sid } }, data: { revokedAt: new Date().toISOString() }, overrideAccess: true, req });
|
|
92
|
+
});
|
|
54
93
|
const onInit = config.onInit;
|
|
55
94
|
return {
|
|
56
95
|
...config,
|
|
@@ -61,12 +100,12 @@ export const hats = (options) => (config) => {
|
|
|
61
100
|
hooks: {
|
|
62
101
|
...c.hooks,
|
|
63
102
|
afterChange: [...(c.hooks?.afterChange ?? []), afterChange],
|
|
64
|
-
afterDelete: [...(c.hooks?.afterDelete ?? [])
|
|
103
|
+
afterDelete: [afterDelete, ...(c.hooks?.afterDelete ?? [])],
|
|
65
104
|
afterLogout: [...(c.hooks?.afterLogout ?? []), afterLogout],
|
|
66
105
|
},
|
|
67
106
|
}
|
|
68
107
|
: c),
|
|
69
|
-
...hatCollections(opts),
|
|
108
|
+
...hatCollections(opts, sql),
|
|
70
109
|
],
|
|
71
110
|
endpoints: [...(config.endpoints ?? []), ...hatEndpoints],
|
|
72
111
|
admin: opts.adminSwitch === false
|
|
@@ -74,6 +113,7 @@ export const hats = (options) => (config) => {
|
|
|
74
113
|
: { ...config.admin, components: { ...config.admin?.components, actions: [...(config.admin?.components?.actions ?? []), '@extantape/payload-plugin-hats/client#HatSwitcher'] } },
|
|
75
114
|
custom: { ...config.custom, hats: opts },
|
|
76
115
|
onInit: async (payload) => {
|
|
116
|
+
unmarkForeignHooks(payload);
|
|
77
117
|
await onInit?.(payload);
|
|
78
118
|
wrapStrategies(payload, opts);
|
|
79
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",
|