@extantape/payload-plugin-hats 0.4.0 → 0.6.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/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 hatsOptions(payload).onEvent?.({ type: 'sessions-revoked', payload, sessions: docs.length, reason });
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
- const before = req.context?.hatsDissolving;
42
- req.context = { ...(req.context ?? {}), hatsDissolving: true };
43
- try {
44
- await asPlugin(req, async () => {
45
- for (const d of docs)
46
- await payload.delete({ collection: MEMBERS, id: d.id, overrideAccess: true, req });
47
- await payload.delete({ collection: LINKS, where: { id: { equals: link } }, overrideAccess: true, req });
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,12 +60,25 @@ export async function sharedLink(payload, a, b, req) {
63
60
  pagination: false,
64
61
  req,
65
62
  });
66
- const [x, y] = docs;
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
- /** The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest. */
71
+ /**
72
+ * Whether a hat is offered to switch into. Only a missing `hidden` (undefined) or exactly `false` offers it: `true`,
73
+ * `null`, `'false'`, `1` or anything else hides it. Hiding only ever refuses switches and shows less, so an unclear
74
+ * value is read the narrow way.
75
+ */
76
+ export const isOffered = (h) => h.hidden === undefined || h.hidden === false;
77
+ /**
78
+ * The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest.
79
+ * `hidden` plays no part here: a session keeps a hidden hat it wears, and the fallback is the narrowest hat even when
80
+ * that one is hidden, because a wider fallback would give the session roles it didn't have.
81
+ */
72
82
  export function wornHat(hats, s) {
73
83
  if (!hats.length)
74
84
  return null;
@@ -93,6 +103,13 @@ export async function applyHat(payload, opts, user) {
93
103
  return null;
94
104
  }
95
105
  if (s?.via) {
106
+ // The account this session was switched in through must still exist. If its delete failed partway (a database
107
+ // error without a transaction), its member row can outlive it: the session is refused all the same.
108
+ const there = await payload.db.count({ collection: opts.users, where: { id: { equals: relId(payload, opts.users, s.via) } } });
109
+ if (!there?.totalDocs) {
110
+ await revokeSessions(payload, { sid: { equals: sid } }, 'account deleted');
111
+ return null;
112
+ }
96
113
  const link = await sharedLink(payload, String(user.id), String(s.via));
97
114
  if (!link || link !== String(s.link)) {
98
115
  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
- /** Runs `fn` with the request marked as the plugin's own, then puts the mark back as it was. */
11
- export declare function asPlugin<T>(req: PayloadRequest, fn: () => Promise<T>): Promise<T>;
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
- /** Runs `fn` with the request marked as the plugin's own, then puts the mark back as it was. */
19
- export async function asPlugin(req, fn) {
20
- const before = req.context?.hatsInternal;
21
- req.context = { ...(req.context ?? {}), hatsInternal: true };
22
- try {
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
- req.context.hatsInternal = before;
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
@@ -1,9 +1,17 @@
1
1
  import type { Payload, PayloadRequest, TypedUser } from 'payload';
2
- /** One role an account can act in. `sensitive` hats need the second factor before switching into them. */
2
+ /**
3
+ * One role an account can act in. `sensitive` hats need the second factor before switching into them.
4
+ *
5
+ * `hidden` hats aren't offered: they're left out of the switch and its Back to button, aren't picked for a switch that
6
+ * names no hat, and a switch into one is refused like a hat the account doesn't hold. A session already wearing one
7
+ * keeps it, and a plain sign-in still wears every role. Only a missing `hidden` or exactly `false` offers the hat; any
8
+ * other value hides it.
9
+ */
3
10
  export type Hat = {
4
11
  id: string;
5
12
  label: string;
6
13
  sensitive?: boolean;
14
+ hidden?: boolean;
7
15
  };
8
16
  /** Who is asking, passed to the site's two-step checks along with the target account. */
9
17
  export type StepUpContext = {
@@ -131,10 +139,17 @@ export type HatsOptions = {
131
139
  adminSwitch?: boolean;
132
140
  /** Hours a confirmation link works. Default 24. */
133
141
  confirmHours?: number;
142
+ /**
143
+ * How long a link request takes to answer, in milliseconds, whatever the address. The records and emails for a
144
+ * request run within this time, so the answer arrives at the same moment whether or not the address has an
145
+ * account. Work still running when it's up carries on after the answer, and is logged. Keep it above your slowest
146
+ * email send, especially on hosts that stop work once a response is sent. Default 2000.
147
+ */
148
+ linkAnswerMs?: number;
134
149
  };
135
150
  export type HatsEvent = {
136
151
  type: 'link-requested';
137
- req: PayloadRequest;
152
+ 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
153
  link: string;
139
154
  by: string;
140
155
  account: string;
@@ -173,3 +188,4 @@ export type ResolvedHatsOptions = Required<Omit<HatsOptions, 'stepUp' | 'stepUpW
173
188
  export declare const LINKS = "hat-links";
174
189
  export declare const MEMBERS = "hat-members";
175
190
  export declare const SESSIONS = "hat-sessions";
191
+ export declare const REQUESTS = "hat-requests";
package/dist/types.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export const LINKS = 'hat-links';
2
2
  export const MEMBERS = 'hat-members';
3
3
  export const SESSIONS = 'hat-sessions';
4
+ export const REQUESTS = 'hat-requests';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.4.0",
3
+ "version": "0.6.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",