@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/endpoints.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { addDataAndFileToRequest, APIError, getFieldsToSign, jwtSign } from 'payload';
2
2
  import { addSessionToUser, generateCookie } from 'payload/shared';
3
3
  import { blockedBy, exactlyTrue } from './access.js';
4
- import { cleanupSessions, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
4
+ import { cleanupSessions, isOffered, 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
- return docs[0] ?? null;
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) {
@@ -55,7 +57,18 @@ async function linkedAccounts(req, userId) {
55
57
  }
56
58
  return { link, linked };
57
59
  }
58
- const defaultShow = ({ hats, linked }) => hats.length > 1 || linked.some((l) => l.hats.length > 1);
60
+ /**
61
+ * Whether the switch is shown (and so allowed). The site's `showSwitch` gets every hat, hidden ones included, with
62
+ * their flags. The default counts only hats that are offered: more than one on this account, or on a linked account.
63
+ * The hat worn now counts too when it's hidden, so a session on a hidden hat with one offered hat to go to can still
64
+ * switch away. Without `hidden` anywhere this is the earlier rule exactly.
65
+ */
66
+ export function showsSwitch(opts, args, worn) {
67
+ if (opts.showSwitch)
68
+ return opts.showSwitch(args);
69
+ const own = args.hats.filter(isOffered).length + (args.hats.some((h) => h.id === worn && !isOffered(h)) ? 1 : 0);
70
+ return own > 1 || args.linked.some((l) => l.hats.filter(isOffered).length > 1);
71
+ }
59
72
  async function blockedReason(req, opts) {
60
73
  if (!opts.blocked)
61
74
  return;
@@ -96,16 +109,21 @@ const me = {
96
109
  account: { id: full.id, label: labelOf(full) },
97
110
  signedInAs: person,
98
111
  hat: worn?.id ?? null,
99
- hats: await Promise.all(hats.map(async (h) => ({ ...h, needsCode: await asks(full, hats, h, true) }))),
100
- linked: await Promise.all(linked.map(async (l) => ({
112
+ // Only offered hats are sent. A hidden hat worn now is named in `wearing`, so the switch can say what's worn,
113
+ // and is never a row. A linked account whose hats are all hidden isn't listed.
114
+ ...(worn && !isOffered(worn) ? { wearing: { id: worn.id, label: worn.label } } : {}),
115
+ hats: await Promise.all(hats.filter(isOffered).map(async (h) => ({ ...h, needsCode: await asks(full, hats, h, true) }))),
116
+ linked: await Promise.all(linked
117
+ .filter((l) => !l.hats.length || l.hats.some(isOffered))
118
+ .map(async (l) => ({
101
119
  id: l.user.id,
102
120
  label: labelOf(l.user),
103
- hats: await Promise.all(l.hats.map(async (h) => ({ ...h, needsCode: await asks(l.user, l.hats, h, false) }))),
121
+ hats: await Promise.all(l.hats.filter(isOffered).map(async (h) => ({ ...h, needsCode: await asks(l.user, l.hats, h, false) }))),
104
122
  }))),
105
123
  link,
106
124
  set,
107
125
  canLink: Boolean(opts.canApproveLinks),
108
- showSwitch: (opts.showSwitch ?? defaultShow)({ user: full, hats, linked }),
126
+ showSwitch: showsSwitch(opts, { user: full, hats, linked }, worn?.id ?? null),
109
127
  maxLinked: opts.maxLinked,
110
128
  });
111
129
  },
@@ -181,6 +199,9 @@ async function switchCore(req, body) {
181
199
  await blockedReason(req, opts);
182
200
  const current = String(full.id);
183
201
  const to = body.account == null || body.account === '' ? current : String(body.account);
202
+ // Only an id exactly as the account has it. Anything else answers as an account that isn't linked, before any query.
203
+ if (to !== current && !exactId(req, opts, body.account))
204
+ refuse('That account isn’t linked to this one.', 403, 'notLinked');
184
205
  let link = null;
185
206
  if (to !== current) {
186
207
  link = await sharedLink(req.payload, current, to, req);
@@ -199,18 +220,24 @@ async function switchCore(req, body) {
199
220
  if (to !== current && usersAuth.verify && target._verified === false)
200
221
  refuse('That account’s email isn’t confirmed yet.', 403, 'unverified');
201
222
  const { linked } = await linkedAccounts(req, current);
202
- if (!(opts.showSwitch ?? defaultShow)({ user: full, hats: opts.hatsOf(full), linked }))
223
+ const s = await sessionBySid(req.payload, state.sid, req);
224
+ const ownHats = opts.hatsOf(full);
225
+ const fromHat = wornHat(ownHats, s)?.id ?? ownHats.at(-1)?.id ?? null;
226
+ if (!showsSwitch(opts, { user: full, hats: ownHats, linked }, fromHat))
203
227
  refuse('Switching isn’t available for this account.', 403, 'notAvailable');
204
228
  const hats = opts.hatsOf(target);
205
- const hat = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
229
+ const picked = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
230
+ // A hidden hat is refused the same way as one the account doesn't hold, whether it was named or would be the
231
+ // default. With no hat named, a linked switch goes to the account's narrowest hat only when that hat is offered: it
232
+ // never moves up to a wider one, so the caller names a hat instead.
233
+ const hat = picked && isOffered(picked) ? picked : undefined;
206
234
  if (!hat)
207
235
  refuse('Choose one of that account’s hats.', 400, 'chooseHat');
208
- const s = await sessionBySid(req.payload, state.sid, req);
209
236
  const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
210
237
  const steppedUp = { ...(s?.steppedUp ?? {}) };
211
238
  let gaveCode = false;
212
239
  const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
213
- const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
240
+ const from = { user: req.user, hat: fromHat };
214
241
  if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
215
242
  if (!opts.stepUp)
216
243
  refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
@@ -292,8 +319,18 @@ const switchHat = {
292
319
  },
293
320
  };
294
321
  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. Confirm from your own email too; then an administrator reviews the link.';
296
- /** POST /api/hats/link { email }: ask to link the acting account with another. Says the same thing whatever happens to the other account. */
322
+ 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.';
323
+ 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}`;
324
+ /** Open link requests one account may have at once. Counted the same whatever the addresses were. */
325
+ const pendingCap = (opts) => opts.maxLinked * 2;
326
+ /**
327
+ * POST /api/hats/link { email }: ask to link the acting account with another. The person asking learns nothing
328
+ * about the address: the answer, the time it takes, their own email, the records they can read and the records
329
+ * written for them are the same whether or not it has an account, whatever state that account is in. Only the
330
+ * other account hears about it, and nothing changes on the asker's side until that account confirms.
331
+ */
332
+ /** What a request's unique `holds` is: the account invited, or a value of its own that holds nothing. */
333
+ const holdFor = (account) => (account ? `account:${String(account.id)}` : `none:${newToken()}`);
297
334
  const requestLink = {
298
335
  path: '/hats/link',
299
336
  method: 'post',
@@ -311,57 +348,94 @@ const requestLink = {
311
348
  refuse('Too many link requests. Try again later.', 429, 'tooMany');
312
349
  const me = String(full.id);
313
350
  const now = new Date();
351
+ // Everything up to here depends only on the asker and what they typed. From here on the answer waits for the
352
+ // same fixed time whatever happens, so how long the work takes says nothing about the address.
353
+ const answer = new Promise((resolve) => setTimeout(resolve, opts.linkAnswerMs));
314
354
  await asPlugin(req, async () => {
315
355
  // Requests nobody confirmed in time don't hold anyone up.
316
- await req.payload.delete({
317
- collection: MEMBERS,
318
- where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] },
319
- overrideAccess: true,
320
- showHiddenFields: true,
321
- req,
322
- });
356
+ // Best effort: what isn't removed now goes on a later request, and the request goes on either way.
357
+ for (const swept of [
358
+ await req.payload.delete({ collection: MEMBERS, where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] }, overrideAccess: true, showHiddenFields: true, req }),
359
+ await req.payload.delete({ collection: REQUESTS, where: { expiresAt: { less_than: now.toISOString() } }, overrideAccess: true, req }),
360
+ ])
361
+ if (swept.errors?.length)
362
+ req.payload.logger.warn({ msg: 'Hats: some expired link requests were not removed; a later request retries' });
323
363
  });
324
364
  const mine = await membershipOf(req, me);
325
365
  const already = mine ? (await members(req, idOf(mine.link))).length : 0;
326
- if (already + (mine ? 1 : 2) > opts.maxLinked)
366
+ if (already + (mine ? 1 : 2) > opts.maxLinked) {
367
+ await answer;
327
368
  refuse(`A set can hold at most ${opts.maxLinked} accounts.`, 400, 'setFull');
328
- const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
329
- const target = docs[0];
330
- if (!target || String(target.id) === me || (await membershipOf(req, String(target.id))))
331
- return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
332
- const hours = opts.confirmHours;
333
- const invite = async (user, link) => {
369
+ }
370
+ const open = await req.payload.count({ collection: REQUESTS, where: { requestedBy: { equals: me } }, overrideAccess: true, req });
371
+ if (open.totalDocs >= pendingCap(opts)) {
372
+ await answer;
373
+ refuse('Too many link requests. Try again later.', 429, 'tooMany');
374
+ }
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
+ // One record for every request, with the same fields. Only a real invitation's token can ever be used.
334
380
  const token = newToken();
335
- await req.payload.create({
336
- collection: MEMBERS,
337
- data: { link, user: user.id, status: 'requested', tokenHash: hashToken(token), tokenExpires: new Date(now.getTime() + hours * 3_600_000).toISOString(), addedBy: me },
381
+ const hours = opts.confirmHours;
382
+ const hold = holdFor(null);
383
+ const request = (await asPlugin(req, () => req.payload.create({
384
+ collection: REQUESTS,
385
+ 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
386
  overrideAccess: true,
339
387
  req,
340
- });
341
- const url = opts.confirmURL ? opts.confirmURL({ req, token }) : `${new URL(req.url ?? 'http://localhost').origin}${req.payload.config.routes.api}/hats/confirm?token=${token}`;
342
- await opts.sendEmail({
343
- payload: req.payload,
344
- to: String(user.email),
345
- subject: 'Confirm linking your accounts',
346
- text: `Someone asked to link ${labelOf(full)} and ${labelOf(target)}, so one person can switch between them.\n\nIf that was you, confirm here within ${hours} hours:\n${url}\n\nIf it wasn’t you, ignore this email: nothing is linked without it.`,
347
- });
388
+ })));
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.
398
+ try {
399
+ await opts.sendEmail({
400
+ payload: req.payload,
401
+ to: String(full.email),
402
+ subject: 'You asked to link an account',
403
+ 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.`,
404
+ });
405
+ }
406
+ catch (err) {
407
+ req.payload.logger.warn({ err }, 'Hats: link request note not sent');
408
+ }
409
+ if (!target)
410
+ return;
411
+ try {
412
+ await opts.sendEmail({
413
+ payload: req.payload,
414
+ to: String(target.email),
415
+ subject: 'Confirm linking your accounts',
416
+ 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.`,
417
+ });
418
+ }
419
+ catch (err) {
420
+ // The invitation never arrived, so its token must never work.
421
+ req.payload.logger.warn({ err }, 'Hats: link invitation not sent');
422
+ await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: { account: null, holds: holdFor(null), tokenHash: null }, overrideAccess: true, req }));
423
+ return;
424
+ }
425
+ // With no set yet, the event waits for confirmation, when the set exists, so `link` is always a real set.
426
+ if (mine)
427
+ await tell(req.payload, req, { type: 'link-requested', req, link: idOf(mine.link), by: me, account: String(target.id) });
348
428
  };
349
- let link = mine ? idOf(mine.link) : null;
350
- try {
351
- await asPlugin(req, async () => {
352
- if (!link)
353
- link = String((await req.payload.create({ collection: LINKS, data: { requestedBy: me, label: `Started by ${labelOf(full)}` }, overrideAccess: true, req })).id);
354
- if (!mine)
355
- await invite(full, link);
356
- await invite(target, link);
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) });
429
+ let finished = false;
430
+ const done = work()
431
+ .catch((err) => req.payload.logger.warn({ err }, 'Hats: link request not finished'))
432
+ .finally(() => {
433
+ finished = true;
434
+ });
435
+ trackWork(done);
436
+ await answer;
437
+ if (!finished)
438
+ void done.then(() => req.payload.logger.info('Hats: a link request finished after its answer. Raise linkAnswerMs if this repeats.'));
365
439
  return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
366
440
  },
367
441
  };
@@ -392,15 +466,123 @@ const confirm = {
392
466
  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
467
  if (!token)
394
468
  return bad();
395
- const { docs } = await req.payload.find({ collection: MEMBERS, where: { tokenHash: { equals: hashToken(token) } }, limit: 1, depth: 0, overrideAccess: true, showHiddenFields: true, pagination: false, req });
469
+ const opts = hatsOptions(req.payload);
470
+ const hash = hashToken(token);
471
+ const thanks = () => page('Confirmed', '<p>Thanks. Once every account in the link is confirmed, an administrator reviews it. You can close this page.</p>');
472
+ // The asker confirming their own side, after the other account confirmed.
473
+ const { docs } = await req.payload.find({ collection: MEMBERS, where: { tokenHash: { equals: hash } }, limit: 1, depth: 0, overrideAccess: true, showHiddenFields: true, pagination: false, req });
396
474
  const m = docs[0];
397
- if (!m || m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
475
+ if (m) {
476
+ if (m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
477
+ return bad();
478
+ if ((await members(req, idOf(m.link))).length > opts.maxLinked)
479
+ return bad();
480
+ 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 }));
481
+ await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: idOf(m.link), account: idOf(m.user) });
482
+ return thanks();
483
+ }
484
+ // The invited account confirming a request. The token works once: the request is deleted before anything else.
485
+ const found = await req.payload.find({ collection: REQUESTS, where: { tokenHash: { equals: hash } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
486
+ const r = found.docs[0];
487
+ if (!r || r.account == null || new Date(r.expiresAt).getTime() < Date.now())
488
+ return bad();
489
+ let gone;
490
+ try {
491
+ gone = await asPlugin(req, () => req.payload.delete({ collection: REQUESTS, where: { and: [{ id: { equals: r.id } }, { tokenHash: { equals: hash } }] }, overrideAccess: true, req }));
492
+ }
493
+ catch {
494
+ return bad(); // the same token confirmed at the same moment: the other confirmation has it
495
+ }
496
+ if (gone.docs?.length !== 1)
497
+ return bad();
498
+ const by = idOf(r.requestedBy);
499
+ const account = idOf(r.account);
500
+ if (by === account)
501
+ return bad();
502
+ const asker = await loadUser(req, by);
503
+ const invited = await loadUser(req, account);
504
+ if (!asker || !invited || (await membershipOf(req, account)))
398
505
  return bad();
399
- 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 }));
400
- await hatsOptions(req.payload).onEvent?.({ type: 'link-confirmed', payload: req.payload, link: idOf(m.link), account: idOf(m.user) });
401
- return page('Confirmed', '<p>Thanks. Once every account in the link is confirmed, an administrator reviews it. You can close this page.</p>');
506
+ const mine = await membershipOf(req, by);
507
+ const existing = mine ? idOf(mine.link) : null;
508
+ // The invitation was for the asker's set as it was then. A set the asker started since, from another of their own
509
+ // requests, is still theirs; any other change (they joined or left a set) needs a new request.
510
+ const was = r.link ? String(r.link) : null;
511
+ if (existing !== was) {
512
+ const started = was === null && existing ? (await req.payload.findByID({ collection: LINKS, id: existing, depth: 0, overrideAccess: true, disableErrors: true, req })) : null;
513
+ if (!started || idOf(started.requestedBy) !== by)
514
+ return bad();
515
+ }
516
+ if (existing && (await members(req, existing)).length + 1 > opts.maxLinked)
517
+ return bad();
518
+ const made = { rows: [] };
519
+ try {
520
+ await asPlugin(req, async () => {
521
+ 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);
522
+ if (!existing)
523
+ made.link = link;
524
+ const now = new Date();
525
+ const row = await req.payload.create({
526
+ collection: MEMBERS,
527
+ 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) },
528
+ overrideAccess: true,
529
+ req,
530
+ });
531
+ made.rows.push(String(row.id));
532
+ if (!mine) {
533
+ // The asker confirms from their own email too, now that the other account has said yes.
534
+ const own = newToken();
535
+ const hours = opts.confirmHours;
536
+ const ownRow = await req.payload.create({
537
+ collection: MEMBERS,
538
+ 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) },
539
+ overrideAccess: true,
540
+ req,
541
+ });
542
+ made.rows.push(String(ownRow.id));
543
+ made.own = own;
544
+ }
545
+ });
546
+ // The site's own callbacks run after the plugin's writes, with its mark off the request.
547
+ if (made.own) {
548
+ const own = made.own;
549
+ const hours = opts.confirmHours;
550
+ await opts.sendEmail({
551
+ payload: req.payload,
552
+ to: String(asker.email),
553
+ subject: 'Confirm linking your accounts',
554
+ 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.`,
555
+ });
556
+ }
557
+ }
558
+ catch (error) {
559
+ // Someone linked one of these accounts a moment ago, or the email didn't go: undo what this made.
560
+ req.payload.logger.warn({ err: error }, 'Hats: link confirmation not recorded');
561
+ await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
562
+ for (const id of made.rows)
563
+ await removeWhere(req.payload, { collection: MEMBERS, where: { id: { equals: id } }, overrideAccess: true, req });
564
+ if (made.link)
565
+ await removeWhere(req.payload, { collection: LINKS, where: { id: { equals: made.link } }, overrideAccess: true, req });
566
+ })).catch((err) => req.payload.logger.warn({ err }, 'Hats: link confirmation clean-up skipped'));
567
+ return bad();
568
+ }
569
+ // The records are written by now, so a handler that fails can't undo or block them: it's logged and skipped.
570
+ if (made.link)
571
+ await tell(req.payload, req, { type: 'link-requested', req, link: made.link, by, account });
572
+ await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: existing ?? made.link, account });
573
+ return thanks();
402
574
  },
403
575
  };
576
+ /** Whether `v` is an account id written the one way the users collection writes its ids. */
577
+ function exactId(req, opts, v) {
578
+ if (typeof v !== 'string' && typeof v !== 'number')
579
+ return false;
580
+ const s = String(v);
581
+ const type = req.payload.collections[opts.users]?.customIDType ?? req.payload.db.defaultIDType;
582
+ if (type === 'number')
583
+ return /^(0|-?[1-9]\d{0,15})$/.test(s) && Number.isSafeInteger(Number(s));
584
+ return typeof v === 'string' && s.length > 0 && s.length <= 256 && s.trim() === s;
585
+ }
404
586
  /** POST /api/hats/unlink { account? }: take an account (default: the acting one) out of the set. Self-serve, at once. */
405
587
  const unlink = {
406
588
  path: '/hats/unlink',
@@ -410,14 +592,21 @@ const unlink = {
410
592
  const { opts, full, person } = await actor(req);
411
593
  await blockedReason(req, opts);
412
594
  const me = String(full.id);
413
- const account = String(req.data?.account ?? me);
595
+ const asked = req.data?.account ?? me;
596
+ const notInSet = () => refuse('That account isn’t in your linked set.', 404, 'notInSet');
597
+ // Only an id exactly as the account has it: no other spelling of a number, and nothing the database would have to
598
+ // make sense of first.
599
+ if (!exactId(req, opts, asked))
600
+ notInSet();
601
+ const account = String(asked);
414
602
  const mine = await membershipOf(req, me);
415
603
  const theirs = account === me ? mine : await membershipOf(req, account);
416
- if (!mine || !theirs || idOf(mine.link) !== idOf(theirs.link))
417
- refuse('That account isn’t in your linked set.', 404, 'notInSet');
604
+ // Another account still waiting to confirm is hidden from the set, so it answers as if it weren't there.
605
+ if (!mine || !theirs || idOf(theirs.user) !== account || idOf(mine.link) !== idOf(theirs.link) || (account !== me && theirs.status === 'requested'))
606
+ notInSet();
418
607
  const link = idOf(theirs.link);
419
608
  await asPlugin(req, () => req.payload.delete({ collection: MEMBERS, id: theirs.id, overrideAccess: true, req }));
420
- await opts.onEvent?.({ type: 'unlinked', payload: req.payload, link, account, by: me });
609
+ await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: me });
421
610
  // If this session was switched in through the account just removed, it ended with the unlink.
422
611
  return json({ ok: true, signedOut: account === me ? person !== me : person === account });
423
612
  },
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
- const afterDelete = async ({ id, req }) => {
56
- await revokeSessions(req.payload, { or: [{ user: { equals: String(id) } }, { via: { equals: String(id) } }] }, 'account deleted', req);
57
- await asPlugin(req, () => req.payload.delete({ collection: MEMBERS, where: { user: { equals: String(id) } }, overrideAccess: true, req }));
58
- };
59
- const afterLogout = async ({ req }) => {
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.update({ collection: SESSIONS, where: { sid: { equals: sid } }, data: { revokedAt: new Date().toISOString() }, overrideAccess: true, req });
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 ?? []), 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
  },
@@ -26,7 +26,17 @@ export declare function revokeSessions(payload: Payload, where: Where, reason: s
26
26
  export declare function dissolveIfAlone(payload: Payload, link: string, req: PayloadRequest): Promise<void>;
27
27
  /** The approved set two accounts are both in, or null. Read fresh every time. */
28
28
  export declare function sharedLink(payload: Payload, a: string, b: string, req?: PayloadRequest): Promise<string | null>;
29
- /** The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest. */
29
+ /**
30
+ * Whether a hat is offered to switch into. Only a missing `hidden` (undefined) or exactly `false` offers it: `true`,
31
+ * `null`, `'false'`, `1` or anything else hides it. Hiding only ever refuses switches and shows less, so an unclear
32
+ * value is read the narrow way.
33
+ */
34
+ export declare const isOffered: (h: Hat) => boolean;
35
+ /**
36
+ * The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest.
37
+ * `hidden` plays no part here: a session keeps a hidden hat it wears, and the fallback is the narrowest hat even when
38
+ * that one is hidden, because a wider fallback would give the session roles it didn't have.
39
+ */
30
40
  export declare function wornHat(hats: Hat[], s: Pick<SessionDoc, 'hat' | 'via'> | null): Hat | null;
31
41
  /**
32
42
  * The user as the rest of the site sees them: narrowed to the hat this session wears. A switched session whose set