@extantape/payload-plugin-hats 0.6.1 → 0.7.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/endpoints.js CHANGED
@@ -29,13 +29,13 @@ async function actor(req) {
29
29
  refuse('Sign in first.', 401, 'signIn');
30
30
  return { opts, user: user, full: full, state: state, person: state.via ?? String(user.id) };
31
31
  }
32
- const loadUser = async (req, id) => (await req.payload.findByID({ collection: hatsOptions(req.payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
33
- const labelOf = (u) => String(u.email ?? u.id);
34
- async function members(req, link) {
32
+ export const loadUser = async (req, id) => (await req.payload.findByID({ collection: hatsOptions(req.payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
33
+ export const labelOf = (u) => String(u.email ?? u.id);
34
+ export async function members(req, link) {
35
35
  const { docs } = await req.payload.find({ collection: MEMBERS, where: { link: { equals: link } }, limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
36
36
  return docs;
37
37
  }
38
- async function membershipOf(req, userId) {
38
+ export 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
41
  // Only a row for exactly this account: on MongoDB the text "null" can match a row whose account was cleared.
@@ -373,9 +373,6 @@ const requestLink = {
373
373
  refuse('Too many link requests. Try again later.', 429, 'tooMany');
374
374
  }
375
375
  const work = async () => {
376
- const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
377
- const found = docs[0];
378
- let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
379
376
  // One record for every request, with the same fields. Only a real invitation's token can ever be used.
380
377
  const token = newToken();
381
378
  const hours = opts.confirmHours;
@@ -386,15 +383,9 @@ const requestLink = {
386
383
  overrideAccess: true,
387
384
  req,
388
385
  })));
389
- // One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
390
- // rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
391
- // the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
392
- // means no invitation, so the asker sees the same thing either way.
393
- const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
394
- const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
395
- if (!claimed)
396
- target = null;
397
- // The asker's own note is the same every time and leaves the address out, so it can't tell them anything.
386
+ // The asker's own note is the same every time and leaves the address out, so it can't tell them anything. It
387
+ // goes before anything that depends on the address (looking it up, checking its set, claiming it), so the
388
+ // work done before it, and when it arrives, is the same for a real address and a made-up one.
398
389
  try {
399
390
  await opts.sendEmail({
400
391
  payload: req.payload,
@@ -406,6 +397,17 @@ const requestLink = {
406
397
  catch (err) {
407
398
  req.payload.logger.warn({ err }, 'Hats: link request note not sent');
408
399
  }
400
+ const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
401
+ const found = docs[0];
402
+ let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
403
+ // One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
404
+ // rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
405
+ // the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
406
+ // means no invitation, so the asker sees the same thing either way.
407
+ const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
408
+ const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
409
+ if (!claimed)
410
+ target = null;
409
411
  if (!target)
410
412
  return;
411
413
  try {
@@ -574,7 +576,7 @@ const confirm = {
574
576
  },
575
577
  };
576
578
  /** Whether `v` is an account id written the one way the users collection writes its ids. */
577
- function exactId(req, opts, v) {
579
+ export function exactId(req, opts, v) {
578
580
  if (typeof v !== 'string' && typeof v !== 'number')
579
581
  return false;
580
582
  const s = String(v);
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ export { hatsStateOf } from './state.js';
5
5
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
6
6
  export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
7
7
  export type { SwitchInput, SwitchResult };
8
+ export { approveLink, checkLinks, linkAccounts } from './link.js';
9
+ export type { ApproveInput, LinkCheck, LinkInput, LinkProblem, LinkReason, LinkResult, LinkRowStatus } from './link.js';
8
10
  /**
9
11
  * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
10
12
  * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
@@ -19,11 +21,5 @@ export declare const switchSession: (req: PayloadRequest, input: {
19
21
  hat?: string;
20
22
  code?: string;
21
23
  }) => Promise<SwitchResult>;
22
- export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, StepUpContext } from './types.js';
23
- /**
24
- * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
25
- * holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
26
- * factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
27
- * the membership or the account's roles change.
28
- */
24
+ export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, LinkSource, StepUpContext } from './types.js';
29
25
  export declare const hats: (options: HatsOptions) => Plugin;
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
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, changeWhere, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks } from './state.js';
4
+ import { asPlugin, changeWhere, holdEvents, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks, watchTransactions } from './state.js';
5
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
8
  export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
9
+ export { approveLink, checkLinks, linkAccounts } from './link.js';
9
10
  /**
10
11
  * 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
12
  * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
@@ -22,6 +23,8 @@ export const switchSession = (req, input) => runSwitch(req, input);
22
23
  * factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
23
24
  * the membership or the account's roles change.
24
25
  */
26
+ /** A set's label once the account that started it is deleted (its old label names that account). */
27
+ const DELETED_STARTER = 'Started by a deleted account';
25
28
  export const hats = (options) => (config) => {
26
29
  const opts = {
27
30
  users: 'users',
@@ -63,9 +66,14 @@ export const hats = (options) => (config) => {
63
66
  // nothing here. It runs before the site's own afterDelete hooks, inside the delete's transaction where there is
64
67
  // one. On SQL databases the foreign keys have already set these columns to null, so null rows go too. Payload runs
65
68
  // 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
69
+ // throws, so the delete fails with it: with a transaction that Payload then ends, the whole delete is undone (a
70
+ // plain error in one document of a default bulk delete doesn't end it, see the README), and without one the caller
67
71
  // still gets the error (a switched session through the deleted account is refused anyway, see `applyHat`).
68
- const afterDelete = ownHook(async ({ id, req }) => {
72
+ // Its events (a leaving, revoked sessions) wait for the delete's transaction to commit, or for this to finish
73
+ // without one (see `holdEvents`). Once that transaction has ended under it, every database call made from here
74
+ // is refused at the moment the adapter looks up its transaction, one already under way included (see
75
+ // `watchTransactions`), so nothing of it is written outside the transaction.
76
+ const afterDelete = ownHook(async ({ id, req }) => holdEvents(req, async () => {
69
77
  const p = req.payload;
70
78
  const me = relId(p, opts.users, id);
71
79
  const mineOrGone = (field) => ({ or: [{ [field]: { equals: me } }, { [field]: { exists: false } }] });
@@ -79,12 +87,15 @@ export const hats = (options) => (config) => {
79
87
  // deleting an account frees nothing the asker could notice. At most one request holds the account.
80
88
  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
89
  // 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 });
90
+ // Only sets this account started: on SQL its foreign key has already cleared `requestedBy`, so a cleared one
91
+ // still carrying a starter's name counts too. Sets cleared before keep their label and aren't written again.
92
+ const startedBy = { or: [{ requestedBy: { equals: me } }, { and: [{ requestedBy: { exists: false } }, { label: { not_equals: DELETED_STARTER } }] }] };
93
+ await changeWhere(p, { collection: LINKS, where: startedBy, data: { requestedBy: null, label: DELETED_STARTER }, overrideAccess: true, req });
83
94
  for (const field of ['addedBy', 'approvedBy'])
84
95
  await changeWhere(p, { collection: MEMBERS, where: { and: [{ [field]: { equals: me } }, { user: { exists: true } }] }, data: { [field]: null }, overrideAccess: true, req });
85
96
  }));
86
97
  await revokeSessions(p, { or: [{ user: { equals: String(id) } }, { via: { equals: String(id) } }] }, 'account deleted', req);
87
- });
98
+ }));
88
99
  const afterLogout = ownHook(async ({ req }) => {
89
100
  const sid = req.user?._sid;
90
101
  if (sid)
@@ -114,6 +125,7 @@ export const hats = (options) => (config) => {
114
125
  custom: { ...config.custom, hats: opts },
115
126
  onInit: async (payload) => {
116
127
  unmarkForeignHooks(payload);
128
+ watchTransactions(payload);
117
129
  await onInit?.(payload);
118
130
  wrapStrategies(payload, opts);
119
131
  },
package/dist/link.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { Payload, PayloadRequest } from 'payload';
2
+ /** Why `linkAccounts` or `approveLink` refused. Each comes with a fixed status; see the README for the table. */
3
+ export type LinkReason = 'linkingOff' | 'blocked' | 'notAccount' | 'sameAccount' | 'otherSet' | 'setFull' | 'notApprover' | 'ownSet' | 'notConfirmed' | 'failed';
4
+ export type LinkRowStatus = 'requested' | 'confirmed' | 'approved';
5
+ /**
6
+ * What a server link came to. `rows` are the member rows of the accounts the call named, as they stand after it.
7
+ * `already` is true when the call asked for what was already so: nothing was written and no event fired.
8
+ */
9
+ export type LinkResult = {
10
+ ok: true;
11
+ link: string | number;
12
+ rows: Array<{
13
+ account: string | number;
14
+ status: LinkRowStatus;
15
+ }>;
16
+ already: boolean;
17
+ } | {
18
+ ok: false;
19
+ status: number;
20
+ reason: LinkReason;
21
+ message: string;
22
+ };
23
+ export type LinkInput = {
24
+ /** The account joining. */
25
+ account: string | number;
26
+ /** An account already in the set, or one to start a set with. */
27
+ with: string | number;
28
+ /** Approve the new rows too, as `req.user`. Default false: they wait for an approver. */
29
+ approve?: boolean;
30
+ };
31
+ export type ApproveInput = {
32
+ /** An account whose member row is confirmed. */
33
+ account: string | number;
34
+ };
35
+ /**
36
+ * Link two accounts from the site's own server code, for a flow where both people already agreed. It runs the
37
+ * plugin's own checks every time and has no option that loosens one. Joins `req`'s transaction when there is one;
38
+ * without one, it writes in order and undoes its own rows on failure. Never throws for a refusal.
39
+ */
40
+ export declare const linkAccounts: (req: PayloadRequest, input: LinkInput) => Promise<LinkResult>;
41
+ /** Approve a confirmed account's row as the approver signed in on `req`, under the admin form's rule. Never throws for a refusal. */
42
+ export declare const approveLink: (req: PayloadRequest, input: ApproveInput) => Promise<LinkResult>;
43
+ /** A rule a set breaks. Sets the plugin wrote itself never break these; rows written by hand may. */
44
+ export type LinkProblem =
45
+ /** More member rows, of any status, than `maxLinked`. */
46
+ 'overFull'
47
+ /** Fewer than two member rows: a set of one isn't a link. */
48
+ | 'alone'
49
+ /** An approved row with no approver recorded. */
50
+ | 'noApprover'
51
+ /** An approved row whose approver is a member of the same set. */
52
+ | 'selfApproved'
53
+ /** A confirmed or approved row that still holds a confirmation token. */
54
+ | 'liveToken'
55
+ /** A row with no account, or whose account doesn't exist. */
56
+ | 'missingAccount'
57
+ /** Member rows that point at a set that doesn't exist. */
58
+ | 'missingSet';
59
+ export type LinkCheck = {
60
+ link: string | number;
61
+ problems: LinkProblem[];
62
+ rows: Array<string | number>;
63
+ };
64
+ /**
65
+ * Lists the sets that break the plugin's rules, for rows written outside it (through the database adapter, say). It
66
+ * only reads and changes nothing: what to do about a set is the site's call. Results hold ids only.
67
+ */
68
+ export declare function checkLinks(payloadOrReq: Payload | PayloadRequest): Promise<LinkCheck[]>;