@extantape/payload-plugin-hats 0.8.0 → 0.9.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/index.js CHANGED
@@ -1,12 +1,16 @@
1
+ import { runDecouple, runDisable, runList, runUnlink } from './accounts.js';
1
2
  import { hatCollections } from './collections.js';
2
- import { hatEndpoints, runSwitch } from './endpoints.js';
3
+ import { hatEndpoints, runRequestLink, runSwitch } from './endpoints.js';
3
4
  import { revokeSessions, wrapStrategies } from './sessions.js';
4
5
  import { REMEMBER_PER } from './stepup.js';
5
6
  import { asPlugin, changeWhere, holdEvents, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks, watchTransactions } from './state.js';
6
7
  import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
7
8
  export { hatsStateOf } from './state.js';
9
+ export { rememberKey, rememberedAt } from './stepup.js';
8
10
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
9
11
  export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
12
+ export { getLinkedSet, HatsRefusal, linkTrusted } from './linking.js';
13
+ export { accountToSignIn, signInAnswer } from './signin.js';
10
14
  export { approveLink, checkLinks, linkAccounts } from './link.js';
11
15
  /**
12
16
  * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
@@ -18,6 +22,39 @@ export { approveLink, checkLinks, linkAccounts } from './link.js';
18
22
  * 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.
19
23
  */
20
24
  export const switchSession = (req, input) => runSwitch(req, input);
25
+ /**
26
+ * Ask to link the signed-in account with the account at `email`, from a site's own route. It runs the same code as
27
+ * `POST /api/hats/link`, the fixed answer time included, and has no option that skips a check. It acts only for
28
+ * `req.user` and never throws for a refusal. `{ ok: true }` means the request was taken, whatever the address: a
29
+ * route should answer 202 with the same words every time.
30
+ */
31
+ export const requestLink = (req, input) => runRequestLink(req, input);
32
+ /**
33
+ * The linked accounts of the signed-in account, as it may see them: itself and the approved accounts. An account
34
+ * still waiting is left out. Listing your own set is always open, in a read-only session too. With `of`, a controller
35
+ * (`canControlAccounts`) reads another account's set, every row with its status. It acts only for `req.user`.
36
+ */
37
+ export const listLinkedAccounts = (req, input = {}) => runList(req, input);
38
+ /**
39
+ * Take one account out of its set, from a site's own route. It runs the same code as `POST /api/hats/unlink`. Your
40
+ * own account can always leave. Another account needs an approved account in the same set, or any account in it
41
+ * while nobody is approved yet, or a controller. It acts only for `req.user` and never throws for a refusal.
42
+ */
43
+ export const unlinkAccount = (req, input = {}) => runUnlink(req, input);
44
+ /**
45
+ * Dissolve the whole set an account is in (default: the signed-in account's). Every account stays whole, and every
46
+ * session switched through the set ends. For an approved account in that set, or a controller. It runs the same code
47
+ * as `POST /api/hats/decouple`, acts only for `req.user` and never throws for a refusal.
48
+ */
49
+ export const decouple = (req, input = {}) => runDecouple(req, input);
50
+ /**
51
+ * Disable one account, through the host's `disable.apply`. For a controller only, and never the account the caller
52
+ * is signed in with or a protected one. The plugin adds no endpoint for it: call it from your own admin route.
53
+ * `dryRun: true` runs every check and writes nothing. It acts only for `req.user` and never throws for a refusal.
54
+ */
55
+ export const disableAccount = (req, input) => runDisable(req, input, false);
56
+ /** Disable every approved account in `account`'s set, with the same rules as `disableAccount`. An account still waiting in the set is never touched. */
57
+ export const disableAll = (req, input) => runDisable(req, input, true);
21
58
  /**
22
59
  * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
23
60
  * holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
@@ -43,6 +80,19 @@ export const hats = (options) => (config) => {
43
80
  throw new Error('hats: linkAnswerMs must be a number of milliseconds, from 0 to 2147483647.');
44
81
  if (opts.stepUp && opts.stepUp.rememberPer !== undefined && !REMEMBER_PER.includes(opts.stepUp.rememberPer))
45
82
  throw new Error("hats: stepUp.rememberPer must be 'account', 'set' or 'hat'.");
83
+ if (opts.canBeLinked !== undefined && typeof opts.canBeLinked !== 'function')
84
+ throw new Error('hats: canBeLinked must be a function. A mistyped value would leave the check off.');
85
+ if (opts.disable !== undefined && (typeof opts.disable !== 'object' || opts.disable === null || typeof opts.disable.isDisabled !== 'function'))
86
+ throw new Error('hats: disable must be an object with an isDisabled function. A mistyped value would leave the check off.');
87
+ // Each of these changes what is allowed or recorded. A mistyped one would be skipped without a word, so it stops the start.
88
+ if (opts.audit !== undefined && typeof opts.audit !== 'function')
89
+ throw new Error('hats: audit must be a function. A mistyped value would leave changes unrecorded.');
90
+ if (opts.disable?.protect !== undefined && typeof opts.disable.protect !== 'function')
91
+ throw new Error('hats: disable.protect must be a function. A mistyped value would leave every account open to a disable.');
92
+ if (opts.disable?.apply !== undefined && typeof opts.disable.apply !== 'function')
93
+ throw new Error('hats: disable.apply must be a function. A mistyped value would disable nothing.');
94
+ if (opts.stepUp?.challenge !== undefined && typeof opts.stepUp.challenge !== 'function')
95
+ throw new Error('hats: stepUp.challenge must be a function. A mistyped value would send no code.');
46
96
  const users = (config.collections ?? []).find((c) => c.slug === opts.users);
47
97
  if (!users?.auth)
48
98
  throw new Error(`hats: no auth collection "${opts.users}".`);
package/dist/link.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Payload, PayloadRequest } from 'payload';
2
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';
3
+ export type LinkReason = 'linkingOff' | 'blocked' | 'notAccount' | 'sameAccount' | 'otherSet' | 'setFull' | 'notApprover' | 'ownSet' | 'notConfirmed' | 'disabled' | 'notLinkable' | 'failed';
4
4
  export type LinkRowStatus = 'requested' | 'confirmed' | 'approved';
5
5
  /**
6
6
  * What a server link came to. `rows` are the member rows of the accounts the call named, as they stand after it.
package/dist/link.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { blockedBy, CANT_CHECK } from './access.js';
2
2
  import { approvalRefusal } from './approval.js';
3
+ import { checkLink } from './linking.js';
3
4
  import { exactId, labelOf, loadUser, members, membershipOf } from './endpoints.js';
4
5
  import { asPlugin, DISSOLVING, hatsOptions, idOf, newToken, relId, removeWhere, serial, tell, withMark } from './state.js';
5
6
  import { LINKS, MEMBERS, REQUESTS } from './types.js';
@@ -10,7 +11,7 @@ class Refused extends Error {
10
11
  this.result = result;
11
12
  }
12
13
  }
13
- const STATUS = { linkingOff: 409, blocked: 409, notAccount: 404, sameAccount: 400, otherSet: 409, setFull: 409, notApprover: 403, ownSet: 403, notConfirmed: 409, failed: 500 };
14
+ const STATUS = { linkingOff: 409, blocked: 409, notAccount: 404, sameAccount: 400, otherSet: 409, setFull: 409, notApprover: 403, ownSet: 403, notConfirmed: 409, disabled: 403, notLinkable: 403, failed: 500 };
14
15
  const refusal = (reason, message) => ({ ok: false, status: STATUS[reason], reason, message });
15
16
  const refuse = (reason, message) => {
16
17
  throw new Refused(refusal(reason, message));
@@ -34,6 +35,17 @@ const MESSAGES = {
34
35
  undoFailed: 'Linking didn’t work, and undoing it didn’t finish either, so these accounts may still be linked. Check them before trying again.',
35
36
  };
36
37
  const setFullMessage = (opts) => `A set can hold at most ${opts.maxLinked} accounts.`;
38
+ /**
39
+ * The shared `checkLink` (the one the endpoints and `linkTrusted` run), turned into this file's refusals, so a server
40
+ * link or approval can't get past `canBeLinked` or `disable.isDisabled` that a person's own request would meet.
41
+ */
42
+ async function sharedCheck(req, opts, args) {
43
+ const check = await checkLink(req.payload, opts, args);
44
+ if (check.ok)
45
+ return;
46
+ const reason = check.reason === 'alreadyLinked' ? 'otherSet' : check.reason;
47
+ refuse(reason, reason === 'setFull' ? setFullMessage(opts) : check.message);
48
+ }
37
49
  const RANK = { requested: 0, confirmed: 1, approved: 2 };
38
50
  /** Runs a server link, turning every refusal and every unexpected error into a result. Never throws. */
39
51
  async function settle(req, what, fn) {
@@ -112,7 +124,7 @@ async function gate(req, opts) {
112
124
  refuse('linkingOff', MESSAGES.linkingOff);
113
125
  if (opts.blocked) {
114
126
  const ask = opts.blocked;
115
- const why = await blockedBy(() => ask(req));
127
+ const why = await blockedBy(() => ask(req, { action: 'link' }));
116
128
  if (why !== null)
117
129
  refuse('blocked', why === CANT_CHECK ? MESSAGES.cantCheck : why);
118
130
  }
@@ -192,6 +204,10 @@ async function approveRow(req, opts, row) {
192
204
  const refused = await approvalRefusal(req, opts, { link, approving: 1, except: String(row.id) });
193
205
  if (refused)
194
206
  refuse(refused.reason, refused.message);
207
+ const member = await loadUser(req, idOf(row.user));
208
+ if (!member)
209
+ refuse('notAccount', MESSAGES.notAccount);
210
+ await sharedCheck(req, opts, { req, set: link, members: [member], joining: [], count: 'approved' });
195
211
  const by = actingId(req, opts);
196
212
  const had = await txState(req);
197
213
  await serial(req, () => asPlugin(req, async () => {
@@ -240,6 +256,7 @@ async function linkCore(req, input) {
240
256
  return { ok: true, link: relId(req.payload, LINKS, existing), rows: await rowsOf(req, [account, other]), already: false };
241
257
  }
242
258
  const adding = existing ? 1 : 2;
259
+ await sharedCheck(req, opts, { req, set: existing, members: existing ? [other] : [], joining: existing ? [account] : [account, other] });
243
260
  // Rows of every status count, so a set written by hand past the limit is never added to.
244
261
  if (existing && (await members(req, existing)).length + adding > opts.maxLinked)
245
262
  refuse('setFull', setFullMessage(opts));
@@ -0,0 +1,119 @@
1
+ import { type Payload, type PayloadRequest } from 'payload';
2
+ import { type HatsUser, type Refusal, type ResolvedHatsOptions } from './types.js';
3
+ export type MemberRow = {
4
+ id: string | number;
5
+ link: unknown;
6
+ user: unknown;
7
+ status: string;
8
+ confirmedAt?: string | null;
9
+ approvedAt?: string | null;
10
+ approvedBy?: unknown;
11
+ };
12
+ /** Every row of a set, read fresh. */
13
+ export declare function rowsOf(payload: Payload, link: string, req?: PayloadRequest): Promise<MemberRow[]>;
14
+ /** The one row an account has, in whatever set and state, or null. */
15
+ export declare function rowOf(payload: Payload, userId: string, req?: PayloadRequest): Promise<MemberRow | null>;
16
+ export declare const loadAccount: (payload: Payload, id: string, req?: PayloadRequest) => Promise<HatsUser | null>;
17
+ /** Whether `v` is an account id written the one way the users collection writes its ids. */
18
+ export declare function exactId(payload: Payload, opts: ResolvedHatsOptions, v: unknown): v is string | number;
19
+ /**
20
+ * The host's word on whether an account is disabled. Only an exact `false` is `no` and only an exact `true` is `yes`.
21
+ * A throw or any other answer is `unclear`, which every caller that would let something through reads as disabled.
22
+ * Without `disable.isDisabled` no account is disabled as far as the plugin knows.
23
+ */
24
+ export declare function disabledState(opts: ResolvedHatsOptions, req: PayloadRequest | undefined, user: HatsUser): Promise<'no' | 'yes' | 'unclear'>;
25
+ /** Whether the host lets this account be in a set. Only an exact `true` from `canBeLinked` allows it; without the hook every account may. */
26
+ export declare function mayBeLinked(opts: ResolvedHatsOptions, req: PayloadRequest, user: HatsUser): Promise<boolean>;
27
+ declare const WORDS: {
28
+ readonly sameAccount: readonly [400, "An account can’t be linked with itself."];
29
+ readonly alreadyLinked: readonly [409, "One of those accounts is already in another linked set."];
30
+ readonly disabled: readonly [403, "A disabled account can’t be linked."];
31
+ readonly notLinkable: readonly [403, "One of those accounts can’t be linked."];
32
+ };
33
+ export type LinkRefusalReason = keyof typeof WORDS | 'setFull';
34
+ export type LinkCheck = {
35
+ ok: true;
36
+ } | (Refusal & {
37
+ reason: LinkRefusalReason;
38
+ });
39
+ /**
40
+ * The one check every way of linking runs: a link request, each confirmation, an approval and `linkTrusted`. It has no
41
+ * option that skips a part, so the paths can't drift.
42
+ *
43
+ * `set` is the set the accounts would share (null when it doesn't exist yet). `members` already have a row in it.
44
+ * `joining` would get one. `slots` counts accounts that would join but aren't known yet. In order:
45
+ * 1. no account twice (`sameAccount`);
46
+ * 2. one set per account: a member's row is in `set`, and a joining account has no row anywhere (`alreadyLinked`);
47
+ * 3. no account the host calls disabled, or can't answer for (`disabled`);
48
+ * 4. every account passes `canBeLinked` (`notLinkable`);
49
+ * 5. the set stays within `maxLinked` (`setFull`). `count: 'rows'` counts every row, `'approved'` only approved ones.
50
+ */
51
+ export declare function checkLink(payload: Payload, opts: ResolvedHatsOptions, args: {
52
+ req: PayloadRequest;
53
+ set: string | null;
54
+ members: HatsUser[];
55
+ joining: HatsUser[];
56
+ slots?: number;
57
+ count?: 'rows' | 'approved';
58
+ }): Promise<LinkCheck>;
59
+ /**
60
+ * Whether a set holds more rows than `maxLinked` right now. Read after a write that added rows: two writers that both
61
+ * passed `checkLink` a moment apart each see the other's rows here, and each takes its own back.
62
+ */
63
+ export declare const overFull: (payload: Payload, opts: ResolvedHatsOptions, set: string, req?: PayloadRequest) => Promise<boolean>;
64
+ /**
65
+ * Whether a set is still there after a write into it: its record exists and, when `member` is given, that account
66
+ * still has its row in it. A set dissolved, or left by the account the link hangs on, while a link was being written
67
+ * makes this false, and the writer takes its own rows back.
68
+ */
69
+ export declare function setStands(payload: Payload, set: string, member: string | null, req?: PayloadRequest): Promise<boolean>;
70
+ /** Thrown by `linkTrusted` when it refuses. `reason` is stable; the message is for logs, never for people. */
71
+ export declare class HatsRefusal extends Error {
72
+ readonly reason: string;
73
+ readonly status: number;
74
+ constructor(reason: string, status: number, message: string);
75
+ }
76
+ export type LinkTrustedInput = {
77
+ /** Two or more account ids, exactly as the users collection writes them. */
78
+ accounts: (string | number)[];
79
+ /** The account that vetted these accounts, or null when the host itself did. Recorded on the rows and in the event. */
80
+ by: string | number | null;
81
+ /** Pass the request the host is already working on, so the writes join its transaction. */
82
+ req?: PayloadRequest;
83
+ };
84
+ export type LinkTrustedResult = {
85
+ ok: true;
86
+ set: string;
87
+ accounts: string[];
88
+ };
89
+ /**
90
+ * Links accounts the host has already vetted, as approved, without the confirmation emails or an approver. Server
91
+ * code only: the plugin registers no endpoint for it, and a host that wraps it in a route owns that route's access.
92
+ *
93
+ * It runs `checkLink`, the same check a link request, a confirmation and an approval run, and has no option that
94
+ * skips it: different accounts, none in another set, none disabled, each passing `canBeLinked`, and the set within
95
+ * `maxLinked`. Accounts already in one set together keep that set, and the others join it; rows still waiting there
96
+ * become approved. A refusal is thrown as a `HatsRefusal` (`tooFew`, `unknownAccount`, `sameAccount`,
97
+ * `alreadyLinked`, `disabled`, `notLinkable`, `setFull`, `auditFailed` when the host's `audit` hook didn't take an
98
+ * entry, or `failed` when a write didn't go through), and nothing is
99
+ * left changed: with a transaction the writes are rolled back, and without one the rows this call made are removed.
100
+ */
101
+ export declare function linkTrusted(payload: Payload, input: LinkTrustedInput): Promise<LinkTrustedResult>;
102
+ export type LinkedSet = {
103
+ link: string | null;
104
+ rows: {
105
+ account: string;
106
+ status: string;
107
+ }[];
108
+ members: string[];
109
+ approved: string[];
110
+ };
111
+ /**
112
+ * A read-only, trusted look at an account's linked set, for server code: every row with its status, the accounts in
113
+ * it, and the approved ones. It checks nobody's access, so a host that puts it behind a route owns that route. An id
114
+ * that isn't written exactly as an account's id, or an account in no set, answers an empty set.
115
+ */
116
+ export declare function getLinkedSet(payload: Payload, accountId: string | number, options?: {
117
+ req?: PayloadRequest;
118
+ }): Promise<LinkedSet>;
119
+ export {};
@@ -0,0 +1,270 @@
1
+ import { commitTransaction, createLocalReq, initTransaction, killTransaction } from 'payload';
2
+ import { exactlyTrue } from './access.js';
3
+ import { asPlugin, AuditFailed, DISSOLVING, hatsOptions, idOf, relId, removeWhere, tell, unmarked, withMark, writeAudit } from './state.js';
4
+ import { LINKS, MEMBERS } from './types.js';
5
+ /** Every row of a set, read fresh. */
6
+ export async function rowsOf(payload, link, req) {
7
+ const { docs } = await payload.find({ collection: MEMBERS, where: { link: { equals: link } }, limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
8
+ return docs;
9
+ }
10
+ /** The one row an account has, in whatever set and state, or null. */
11
+ export async function rowOf(payload, userId, req) {
12
+ const { docs } = await payload.find({ collection: MEMBERS, where: { user: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
13
+ const row = docs[0] ?? null;
14
+ // Only a row for exactly this account: on MongoDB the text "null" can match a row whose account was cleared.
15
+ return row && row.user != null && idOf(row.user) === userId ? row : null;
16
+ }
17
+ export const loadAccount = async (payload, id, req) => (await payload.findByID({ collection: hatsOptions(payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
18
+ /** Whether `v` is an account id written the one way the users collection writes its ids. */
19
+ export function exactId(payload, opts, v) {
20
+ if (typeof v !== 'string' && typeof v !== 'number')
21
+ return false;
22
+ const s = String(v);
23
+ const type = payload.collections[opts.users]?.customIDType ?? payload.db.defaultIDType;
24
+ if (type === 'number')
25
+ return /^(0|-?[1-9]\d{0,15})$/.test(s) && Number.isSafeInteger(Number(s));
26
+ return typeof v === 'string' && s.length > 0 && s.length <= 256 && s.trim() === s;
27
+ }
28
+ /**
29
+ * The host's word on whether an account is disabled. Only an exact `false` is `no` and only an exact `true` is `yes`.
30
+ * A throw or any other answer is `unclear`, which every caller that would let something through reads as disabled.
31
+ * Without `disable.isDisabled` no account is disabled as far as the plugin knows.
32
+ */
33
+ export async function disabledState(opts, req, user) {
34
+ const read = opts.disable?.isDisabled;
35
+ if (typeof read !== 'function')
36
+ return 'no';
37
+ try {
38
+ const answer = await unmarked(req, () => read(user));
39
+ return answer === false ? 'no' : answer === true ? 'yes' : 'unclear';
40
+ }
41
+ catch {
42
+ return 'unclear';
43
+ }
44
+ }
45
+ /** Whether the host lets this account be in a set. Only an exact `true` from `canBeLinked` allows it; without the hook every account may. */
46
+ export async function mayBeLinked(opts, req, user) {
47
+ const ask = opts.canBeLinked;
48
+ if (!ask)
49
+ return true;
50
+ return exactlyTrue(() => unmarked(req, () => ask({ req, user })));
51
+ }
52
+ const WORDS = {
53
+ sameAccount: [400, 'An account can’t be linked with itself.'],
54
+ alreadyLinked: [409, 'One of those accounts is already in another linked set.'],
55
+ disabled: [403, 'A disabled account can’t be linked.'],
56
+ notLinkable: [403, 'One of those accounts can’t be linked.'],
57
+ };
58
+ /**
59
+ * The one check every way of linking runs: a link request, each confirmation, an approval and `linkTrusted`. It has no
60
+ * option that skips a part, so the paths can't drift.
61
+ *
62
+ * `set` is the set the accounts would share (null when it doesn't exist yet). `members` already have a row in it.
63
+ * `joining` would get one. `slots` counts accounts that would join but aren't known yet. In order:
64
+ * 1. no account twice (`sameAccount`);
65
+ * 2. one set per account: a member's row is in `set`, and a joining account has no row anywhere (`alreadyLinked`);
66
+ * 3. no account the host calls disabled, or can't answer for (`disabled`);
67
+ * 4. every account passes `canBeLinked` (`notLinkable`);
68
+ * 5. the set stays within `maxLinked` (`setFull`). `count: 'rows'` counts every row, `'approved'` only approved ones.
69
+ */
70
+ export async function checkLink(payload, opts, args) {
71
+ const { req, set } = args;
72
+ const no = (reason) => ({ ok: false, reason, status: WORDS[reason][0], message: WORDS[reason][1] });
73
+ const all = [...args.members, ...args.joining];
74
+ const ids = all.map((a) => String(a.id));
75
+ if (new Set(ids).size !== ids.length)
76
+ return no('sameAccount');
77
+ for (const m of args.members) {
78
+ const row = await rowOf(payload, String(m.id), req);
79
+ if (!row || set === null || idOf(row.link) !== set)
80
+ return no('alreadyLinked');
81
+ }
82
+ for (const j of args.joining)
83
+ if (await rowOf(payload, String(j.id), req))
84
+ return no('alreadyLinked');
85
+ for (const a of all)
86
+ if ((await disabledState(opts, req, a)) !== 'no')
87
+ return no('disabled');
88
+ for (const a of all)
89
+ if (!(await mayBeLinked(opts, req, a)))
90
+ return no('notLinkable');
91
+ const rows = set === null ? [] : await rowsOf(payload, set, req);
92
+ const others = rows.filter((r) => !ids.includes(idOf(r.user)) && (args.count !== 'approved' || r.status === 'approved')).length;
93
+ if (others + ids.length + (args.slots ?? 0) > opts.maxLinked)
94
+ return { ok: false, reason: 'setFull', status: 400, message: `A set can hold at most ${opts.maxLinked} accounts.` };
95
+ return { ok: true };
96
+ }
97
+ /**
98
+ * Whether a set holds more rows than `maxLinked` right now. Read after a write that added rows: two writers that both
99
+ * passed `checkLink` a moment apart each see the other's rows here, and each takes its own back.
100
+ */
101
+ export const overFull = async (payload, opts, set, req) => (await rowsOf(payload, set, req)).length > opts.maxLinked;
102
+ /**
103
+ * Whether a set is still there after a write into it: its record exists and, when `member` is given, that account
104
+ * still has its row in it. A set dissolved, or left by the account the link hangs on, while a link was being written
105
+ * makes this false, and the writer takes its own rows back.
106
+ */
107
+ export async function setStands(payload, set, member, req) {
108
+ const doc = await payload.findByID({ collection: LINKS, id: set, depth: 0, overrideAccess: true, disableErrors: true, req });
109
+ if (!doc)
110
+ return false;
111
+ if (member === null)
112
+ return true;
113
+ const row = await rowOf(payload, member, req);
114
+ return Boolean(row && idOf(row.link) === set);
115
+ }
116
+ /** Thrown by `linkTrusted` when it refuses. `reason` is stable; the message is for logs, never for people. */
117
+ export class HatsRefusal extends Error {
118
+ reason;
119
+ status;
120
+ constructor(reason, status, message) {
121
+ super(message);
122
+ this.name = 'HatsRefusal';
123
+ this.reason = reason;
124
+ this.status = status;
125
+ }
126
+ }
127
+ const OVER = Symbol('over maxLinked after the write');
128
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
129
+ /**
130
+ * Links accounts the host has already vetted, as approved, without the confirmation emails or an approver. Server
131
+ * code only: the plugin registers no endpoint for it, and a host that wraps it in a route owns that route's access.
132
+ *
133
+ * It runs `checkLink`, the same check a link request, a confirmation and an approval run, and has no option that
134
+ * skips it: different accounts, none in another set, none disabled, each passing `canBeLinked`, and the set within
135
+ * `maxLinked`. Accounts already in one set together keep that set, and the others join it; rows still waiting there
136
+ * become approved. A refusal is thrown as a `HatsRefusal` (`tooFew`, `unknownAccount`, `sameAccount`,
137
+ * `alreadyLinked`, `disabled`, `notLinkable`, `setFull`, `auditFailed` when the host's `audit` hook didn't take an
138
+ * entry, or `failed` when a write didn't go through), and nothing is
139
+ * left changed: with a transaction the writes are rolled back, and without one the rows this call made are removed.
140
+ */
141
+ export async function linkTrusted(payload, input) {
142
+ const opts = hatsOptions(payload);
143
+ const req = input?.req ?? (await createLocalReq({}, payload));
144
+ const list = Array.isArray(input?.accounts) ? input.accounts : [];
145
+ if (list.length < 2)
146
+ throw new HatsRefusal('tooFew', 400, 'Hats: linkTrusted needs at least two accounts.');
147
+ const unknown = () => new HatsRefusal('unknownAccount', 404, 'Hats: linkTrusted was given an id that is no account.');
148
+ if (!list.every((a) => exactId(payload, opts, a)))
149
+ throw unknown();
150
+ const ids = list.map(String);
151
+ if (new Set(ids).size !== ids.length)
152
+ throw new HatsRefusal('sameAccount', 400, 'Hats: linkTrusted was given the same account twice.');
153
+ if (input.by !== null && !exactId(payload, opts, input.by))
154
+ throw unknown();
155
+ const by = input.by === null ? null : String(input.by);
156
+ const vetter = by === null ? null : await loadAccount(payload, by, req);
157
+ if (by !== null && !vetter)
158
+ throw unknown();
159
+ const users = [];
160
+ for (const id of ids) {
161
+ const u = await loadAccount(payload, id, req);
162
+ if (!u)
163
+ throw unknown();
164
+ users.push(u);
165
+ }
166
+ /** A fresh read of where every account stands, and the shared check on it. */
167
+ const plan = async () => {
168
+ const rows = new Map();
169
+ for (const id of ids) {
170
+ const row = await rowOf(payload, id, req);
171
+ if (row)
172
+ rows.set(id, row);
173
+ }
174
+ const sets = new Set([...rows.values()].map((r) => idOf(r.link)));
175
+ if (sets.size > 1)
176
+ throw new HatsRefusal('alreadyLinked', WORDS.alreadyLinked[0], 'Hats: those accounts are in different linked sets.');
177
+ const set = sets.size ? [...sets][0] : null;
178
+ const check = await checkLink(payload, opts, { req, set, members: users.filter((u) => rows.has(String(u.id))), joining: users.filter((u) => !rows.has(String(u.id))) });
179
+ if (!check.ok)
180
+ throw new HatsRefusal(check.reason, check.status, `Hats: linkTrusted refused (${check.reason}).`);
181
+ return { set, rows };
182
+ };
183
+ for (let attempt = 0;; attempt++) {
184
+ const { set, rows } = await plan();
185
+ const started = await initTransaction(req);
186
+ const undo = [];
187
+ try {
188
+ const now = new Date().toISOString();
189
+ const byRel = by === null ? null : relId(payload, opts.users, by);
190
+ const link = await asPlugin(req, async () => {
191
+ let link = set;
192
+ if (link === null) {
193
+ const made = await payload.create({ collection: LINKS, data: { requestedBy: byRel, label: vetter ? `Linked by ${String(vetter.email ?? vetter.id)}` : 'Linked by the site' }, overrideAccess: true, req });
194
+ link = String(made.id);
195
+ const id = link;
196
+ undo.push(() => removeWhere(payload, { collection: LINKS, where: { id: { equals: id } }, overrideAccess: true, req }));
197
+ }
198
+ else {
199
+ // Touching the set's own record makes two transactions that change one set collide, so only one commits.
200
+ await payload.db.updateOne({ collection: LINKS, id: relId(payload, LINKS, link), data: { updatedAt: now }, req, returning: false });
201
+ }
202
+ for (const u of users) {
203
+ const row = rows.get(String(u.id));
204
+ if (!row) {
205
+ const made = await payload.create({
206
+ collection: MEMBERS,
207
+ data: { link: relId(payload, LINKS, link), user: relId(payload, opts.users, u.id), status: 'approved', addedBy: byRel, confirmedAt: now, approvedBy: byRel, approvedAt: now },
208
+ overrideAccess: true,
209
+ req,
210
+ });
211
+ undo.push(() => removeWhere(payload, { collection: MEMBERS, where: { id: { equals: made.id } }, overrideAccess: true, req }));
212
+ }
213
+ else if (row.status !== 'approved') {
214
+ await payload.update({ collection: MEMBERS, id: row.id, data: { status: 'approved', confirmedAt: row.confirmedAt ?? now, approvedBy: byRel, approvedAt: now, tokenHash: null, tokenExpires: null }, overrideAccess: true, req });
215
+ undo.push(() => payload.update({ collection: MEMBERS, id: row.id, data: { status: row.status, confirmedAt: row.confirmedAt ?? null, approvedBy: null, approvedAt: null }, overrideAccess: true, req }));
216
+ }
217
+ }
218
+ return link;
219
+ });
220
+ if (await overFull(payload, opts, link, req))
221
+ throw OVER;
222
+ // The set was dissolved while this was being written: the next round reads again and starts from what is true now.
223
+ if (!(await setStands(payload, link, null, req)))
224
+ throw new Error('Hats: the set was dissolved while a trusted link was being written');
225
+ await writeAudit(payload, req, ids.map((account) => ({ action: 'linked-trusted', actor: by, account, via: null, hat: null, reason: null })));
226
+ if (started)
227
+ await commitTransaction(req);
228
+ await tell(payload, req, { type: 'linked-trusted', payload, link, accounts: ids, by });
229
+ return { ok: true, set: link, accounts: ids };
230
+ }
231
+ catch (error) {
232
+ if (started)
233
+ await killTransaction(req);
234
+ else
235
+ await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
236
+ for (const step of undo.reverse())
237
+ await step();
238
+ })).catch((err) => payload.logger.warn({ err }, 'Hats: a trusted link that failed left rows behind'));
239
+ if (error === OVER)
240
+ throw new HatsRefusal('setFull', 400, 'Hats: linkTrusted refused (setFull).');
241
+ if (error instanceof AuditFailed)
242
+ throw new HatsRefusal('auditFailed', 500, 'Hats: linkTrusted was not recorded by the audit hook, so nothing was linked.');
243
+ if (error instanceof HatsRefusal)
244
+ throw error;
245
+ // A write was refused, most often because someone linked one of these accounts a moment ago. The next round
246
+ // reads everything again, so the answer names what is true now.
247
+ if (attempt >= 2) {
248
+ payload.logger.warn({ err: error }, 'Hats: a trusted link was not written');
249
+ throw new HatsRefusal('failed', 500, 'Hats: linkTrusted could not write the link.');
250
+ }
251
+ await sleep(25 * (attempt + 1));
252
+ }
253
+ }
254
+ }
255
+ /**
256
+ * A read-only, trusted look at an account's linked set, for server code: every row with its status, the accounts in
257
+ * it, and the approved ones. It checks nobody's access, so a host that puts it behind a route owns that route. An id
258
+ * that isn't written exactly as an account's id, or an account in no set, answers an empty set.
259
+ */
260
+ export async function getLinkedSet(payload, accountId, options = {}) {
261
+ const none = { link: null, rows: [], members: [], approved: [] };
262
+ if (!exactId(payload, hatsOptions(payload), accountId))
263
+ return none;
264
+ const mine = await rowOf(payload, String(accountId), options.req);
265
+ if (!mine)
266
+ return none;
267
+ const link = idOf(mine.link);
268
+ const rows = (await rowsOf(payload, link, options.req)).filter((r) => r.user != null).map((r) => ({ account: idOf(r.user), status: r.status }));
269
+ return { link, rows, members: rows.map((r) => r.account), approved: rows.filter((r) => r.status === 'approved').map((r) => r.account) };
270
+ }
package/dist/sessions.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { disabledState, loadAccount } from './linking.js';
1
2
  import { asPlugin, attachState, DISSOLVING, hatsOptions, idOf, relId, removeWhere, stillInTransaction, tell, withMark } from './state.js';
2
3
  import { LINKS, MEMBERS, SESSIONS } from './types.js';
3
4
  export async function sessionBySid(payload, sid, req) {
@@ -120,6 +121,13 @@ export async function applyHat(payload, opts, user) {
120
121
  await revokeSessions(payload, { sid: { equals: sid } }, 'no longer linked');
121
122
  return null;
122
123
  }
124
+ // The person who first signed in must still be allowed in. A host that disabled them outside disableAccount
125
+ // ends the switched session here, on the next request.
126
+ const first = await loadAccount(payload, String(s.via));
127
+ if (!first || (await disabledState(opts, undefined, first)) !== 'no') {
128
+ await revokeSessions(payload, { sid: { equals: sid } }, 'first account disabled');
129
+ return null;
130
+ }
123
131
  }
124
132
  const hats = opts.hatsOf(user);
125
133
  // A session the plugin keeps a record for (switched into, or wearing a hat) whose account now has no hats at all,
@@ -0,0 +1,62 @@
1
+ import { type Payload, type PayloadRequest } from 'payload';
2
+ export type AccountToSignInOptions = {
3
+ /** The caller's own request. The answer is for `req.user`, so without it every call is refused (`signIn`). */
4
+ req?: PayloadRequest;
5
+ /**
6
+ * The default hat the host keeps for the target account, if it keeps one. The plugin stores none. A hat the account
7
+ * doesn't hold, or one that is hidden, is passed over for the account's narrowest hat.
8
+ */
9
+ defaultHat?: string | null;
10
+ };
11
+ export type AccountToSignInResult = {
12
+ ok: true;
13
+ /** The linked account, as asked. */
14
+ account: string;
15
+ /** That account's own default hat, or null when it has no hats. Never the hat worn on the caller's account. */
16
+ hat: string | null;
17
+ /** The account the caller signed in with. */
18
+ via: string;
19
+ /** Whether `hat` still needs a code. The answer never carries a session either way. */
20
+ needsStepUp: boolean;
21
+ } | {
22
+ ok: false; /** For server code and logs only. Never send it to a browser: see `signInAnswer`. */
23
+ reason: string;
24
+ };
25
+ /**
26
+ * Whether the caller may sign in with a linked account, and the hat that account would start in. A read for server
27
+ * code: it writes nothing and issues no session, cookie or token. A session for the account comes only from
28
+ * `switchSession`, which runs every check again, the code for a sensitive hat included.
29
+ *
30
+ * It answers ok only for an account with an approved row in the same set as the account the caller is acting as,
31
+ * read from the database on every call. It is refused for the caller's own account (`sameAccount`), while `blocked`
32
+ * says no (`blocked`, asked with the action `signIn`, which is where a host refuses a masquerade), for an account
33
+ * Payload's own login would turn away (`locked`, `unverified`), and by the shared link check (`disabled`,
34
+ * `notLinkable`, `setFull`). Everything else is `notLinked`.
35
+ *
36
+ * `hat` is the target account's own: the host's `defaultHat` when the account holds it and it is offered, otherwise
37
+ * the account's narrowest hat. The hat worn on the caller's account plays no part.
38
+ *
39
+ * It never throws for a refusal, and an error from a host hook is a refusal too (`failed`).
40
+ */
41
+ export declare function accountToSignIn(payload: Payload, accountId: string | number, options?: AccountToSignInOptions): Promise<AccountToSignInResult>;
42
+ export type SignInAnswer = {
43
+ status: 200;
44
+ body: {
45
+ ok: true;
46
+ account: string;
47
+ hat: string | null;
48
+ needsStepUp: boolean;
49
+ };
50
+ } | {
51
+ status: 403;
52
+ body: {
53
+ ok: false;
54
+ reason: 'notAvailable';
55
+ message: string;
56
+ };
57
+ };
58
+ /**
59
+ * What a route may send to a browser for an `accountToSignIn` result. Every refusal gets the one same status and body,
60
+ * whatever its reason, so the answer can't be used to learn who is linked to whom.
61
+ */
62
+ export declare function signInAnswer(result: AccountToSignInResult): SignInAnswer;