@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/signin.js ADDED
@@ -0,0 +1,109 @@
1
+ import { APIError } from 'payload';
2
+ import { actor, blockedReason, loginBar, refuse } from './endpoints.js';
3
+ import { checkLink, disabledState, exactId, loadAccount, mayBeLinked } from './linking.js';
4
+ import { isOffered, sessionBySid, sharedLink, wornHat } from './sessions.js';
5
+ import { tell } from './state.js';
6
+ import { needsStepUp, remembered } from './stepup.js';
7
+ /**
8
+ * Whether the caller may sign in with a linked account, and the hat that account would start in. A read for server
9
+ * code: it writes nothing and issues no session, cookie or token. A session for the account comes only from
10
+ * `switchSession`, which runs every check again, the code for a sensitive hat included.
11
+ *
12
+ * It answers ok only for an account with an approved row in the same set as the account the caller is acting as,
13
+ * read from the database on every call. It is refused for the caller's own account (`sameAccount`), while `blocked`
14
+ * says no (`blocked`, asked with the action `signIn`, which is where a host refuses a masquerade), for an account
15
+ * Payload's own login would turn away (`locked`, `unverified`), and by the shared link check (`disabled`,
16
+ * `notLinkable`, `setFull`). Everything else is `notLinked`.
17
+ *
18
+ * `hat` is the target account's own: the host's `defaultHat` when the account holds it and it is offered, otherwise
19
+ * the account's narrowest hat. The hat worn on the caller's account plays no part.
20
+ *
21
+ * It never throws for a refusal, and an error from a host hook is a refusal too (`failed`).
22
+ */
23
+ export async function accountToSignIn(payload, accountId, options = {}) {
24
+ try {
25
+ return await core(payload, accountId, options ?? {});
26
+ }
27
+ catch (error) {
28
+ if (error instanceof APIError) {
29
+ const reason = error.data?.reason;
30
+ return { ok: false, reason: typeof reason === 'string' ? reason : 'failed' };
31
+ }
32
+ payload?.logger?.warn({ err: error }, 'Hats: accountToSignIn refused after an unexpected error');
33
+ return { ok: false, reason: 'failed' };
34
+ }
35
+ }
36
+ async function core(payload, accountId, options) {
37
+ const req = options.req;
38
+ // The caller is whoever `req.user` is, on this Payload. Nothing else says who is asking.
39
+ if (!req || req.payload !== payload)
40
+ refuse('Sign in first.', 401, 'signIn');
41
+ const { opts, full, state, person } = await actor(req, 401, false);
42
+ await blockedReason(req, opts, 'signIn');
43
+ const me = String(full.id);
44
+ const notLinked = () => refuse('That account isn’t linked to this one.', 403, 'notLinked');
45
+ // Only an id exactly as the account has it, before any query.
46
+ if (!exactId(payload, opts, accountId))
47
+ notLinked();
48
+ const to = String(accountId);
49
+ // Both rows approved and in one set, read now. An account in another set, one still waiting and one that doesn't
50
+ // exist all answer the same.
51
+ const link = to === me ? null : await sharedLink(payload, me, to, req);
52
+ if (to !== me && !link)
53
+ notLinked();
54
+ const target = to === me ? full : await loadAccount(payload, to, req);
55
+ if (!target)
56
+ notLinked();
57
+ // The shared check every way of linking runs. It refuses the caller's own account first (`sameAccount`), then a
58
+ // disabled account, one `canBeLinked` rules out, and a set over `maxLinked`.
59
+ const check = await checkLink(payload, opts, { req: req, set: link, members: [full, target], joining: [], count: 'approved' });
60
+ if (!check.ok) {
61
+ // A row that moved between the two reads: no longer the link that was read.
62
+ if (check.reason === 'alreadyLinked')
63
+ notLinked();
64
+ refuse(check.message, check.status, check.reason);
65
+ }
66
+ // The person who first signed in is held to the same checks as the switch holds them to: if they have become a minor
67
+ // or been disabled since, nothing is offered on their session.
68
+ if (to !== me && String(person) !== me) {
69
+ const first = await loadAccount(payload, String(person), req);
70
+ if (!first || (await disabledState(opts, req, first)) !== 'no' || !(await mayBeLinked(opts, req, first)))
71
+ refuse('Switching isn’t available for that account.', 403, 'notAvailable');
72
+ }
73
+ const bar = loginBar(payload, opts, target);
74
+ if (bar === 'locked')
75
+ refuse('That account is locked. Try again later.', 403, 'locked');
76
+ if (bar === 'unverified')
77
+ refuse('That account’s email isn’t confirmed yet.', 403, 'unverified');
78
+ // The target's own hats only. A stored default the account no longer holds falls to the narrowest, never a wider one.
79
+ const hats = opts.hatsOf(target);
80
+ const kept = typeof options.defaultHat === 'string' ? hats.find((h) => h.id === options.defaultHat) : undefined;
81
+ const hat = kept && isOffered(kept) ? kept : (hats[0] ?? null);
82
+ // A hidden narrowest hat isn't offered, and the answer never moves up to a wider one: the switch refuses the same way.
83
+ if (hat && !isOffered(hat))
84
+ refuse('Choose one of that account’s hats.', 400, 'chooseHat');
85
+ // The same question the switch asks, with the same memory, so this answer and the switch agree.
86
+ let code = false;
87
+ if (hat) {
88
+ const s = await sessionBySid(payload, state.sid, req);
89
+ const own = opts.hatsOf(full);
90
+ const from = { user: req.user, hat: wornHat(own, s)?.id ?? own.at(-1)?.id ?? null };
91
+ code = (await needsStepUp(opts, { req: req, from, target: target, hats, hat })) && !remembered(opts, s?.steppedUp, to, link);
92
+ }
93
+ const result = { ok: true, account: to, hat: hat?.id ?? null, via: person, needsStepUp: code };
94
+ await tell(payload, req, { type: 'sign-in-account', req: req, from: me, account: to, hat: result.hat, via: person, needsStepUp: code });
95
+ return result;
96
+ }
97
+ const REFUSED = Object.freeze({
98
+ status: 403,
99
+ body: Object.freeze({ ok: false, reason: 'notAvailable', message: 'You can’t sign in with that account.' }),
100
+ });
101
+ /**
102
+ * What a route may send to a browser for an `accountToSignIn` result. Every refusal gets the one same status and body,
103
+ * whatever its reason, so the answer can't be used to learn who is linked to whom.
104
+ */
105
+ export function signInAnswer(result) {
106
+ if (!result || result.ok !== true)
107
+ return REFUSED;
108
+ return { status: 200, body: { ok: true, account: result.account, hat: result.hat, needsStepUp: result.needsStepUp } };
109
+ }
package/dist/state.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Payload, PayloadRequest, Where } from 'payload';
2
- import type { HatsEvent, HatsState, HatsUser, ResolvedHatsOptions } from './types.js';
2
+ import type { AuditEntry, HatsEvent, HatsState, HatsUser, ResolvedHatsOptions } from './types.js';
3
3
  /** Attaches the session's hat state to a user without it ever being serialised into a response. */
4
4
  export declare function attachState<T extends object>(user: T, state: HatsState): T;
5
5
  /** The hat state of a signed-in user (or request), for audit logs and the site's own checks. */
@@ -84,6 +84,16 @@ export declare function safeName(error: unknown): string;
84
84
  * `TELL_MS` is left to finish unwaited, so a handler can never block or undo what already happened.
85
85
  */
86
86
  export declare function tell(payload: Payload, req: PayloadRequest | undefined, event: HatsEvent): Promise<void>;
87
+ /** Thrown when the host's `audit` hook didn't take an entry. The change it was for must not be committed. */
88
+ export declare class AuditFailed extends Error {
89
+ constructor();
90
+ }
91
+ /**
92
+ * Gives the host's `audit` hook its entries, one at a time, awaited, with the plugin's marks off. Called after the
93
+ * writes and before they are committed. A hook that throws stops the call with `AuditFailed`; it is logged by its
94
+ * error's name only, since a message can carry what the entry was about. Without the hook this does nothing.
95
+ */
96
+ export declare function writeAudit(payload: Payload, req: PayloadRequest, entries: Omit<AuditEntry, 'req'>[]): Promise<void>;
87
97
  export declare function trackWork(p: Promise<unknown>): void;
88
98
  /** Resolves once every link request's work has finished, including any started meanwhile. */
89
99
  export declare function linkWorkSettled(): Promise<void>;
package/dist/state.js CHANGED
@@ -389,6 +389,32 @@ async function send(payload, req, event) {
389
389
  clearTimeout(timer);
390
390
  }
391
391
  }
392
+ /** Thrown when the host's `audit` hook didn't take an entry. The change it was for must not be committed. */
393
+ export class AuditFailed extends Error {
394
+ constructor() {
395
+ super('Hats: the audit hook did not take an entry');
396
+ this.name = 'AuditFailed';
397
+ }
398
+ }
399
+ /**
400
+ * Gives the host's `audit` hook its entries, one at a time, awaited, with the plugin's marks off. Called after the
401
+ * writes and before they are committed. A hook that throws stops the call with `AuditFailed`; it is logged by its
402
+ * error's name only, since a message can carry what the entry was about. Without the hook this does nothing.
403
+ */
404
+ export async function writeAudit(payload, req, entries) {
405
+ const audit = hatsOptions(payload).audit;
406
+ if (typeof audit !== 'function')
407
+ return;
408
+ for (const entry of entries) {
409
+ try {
410
+ await unmarked(req, () => audit({ ...entry, req }));
411
+ }
412
+ catch (error) {
413
+ payload.logger.error({ msg: `Hats: the audit hook failed on ${entry.action} (${safeName(error)})` });
414
+ throw new AuditFailed();
415
+ }
416
+ }
417
+ }
392
418
  /** Link requests still working after their answer, so tests (and a graceful shutdown) can wait for them. */
393
419
  const working = new Set();
394
420
  export function trackWork(p) {
package/dist/stepup.d.ts CHANGED
@@ -9,6 +9,20 @@ export declare const REMEMBER_PER: readonly unknown[];
9
9
  * value that isn't one of the three, has no key: nothing is remembered and nothing is written.
10
10
  */
11
11
  export declare const memoryKey: (opts: ResolvedHatsOptions, account: string, set: string | null, hat?: string | null) => string | null;
12
+ /**
13
+ * The same key as a pure function, for a site that reads `steppedUp` on a session itself (for example to check a code
14
+ * given for a wider hat). `per` is `stepUp.rememberPer` as the site set it. Returns `null` when there is no key.
15
+ */
16
+ export declare const rememberKey: (per: unknown, w: {
17
+ account: string;
18
+ set?: string | null;
19
+ hat?: string | null;
20
+ }) => string | null;
21
+ /**
22
+ * When a code was given under `key`, as an ISO string, or `null` when it wasn't or `steppedUp` has no such entry.
23
+ * Reads own entries only. It does not check the age: compare it with `stepUp.rememberMinutes` (default 180).
24
+ */
25
+ export declare const rememberedAt: (steppedUp: Record<string, string> | null | undefined, key: string | null) => string | null;
12
26
  /** Whether a good code was given recently enough to count. */
13
27
  export declare const remembered: (opts: ResolvedHatsOptions, steppedUp: Record<string, string> | null | undefined, account: string, set: string | null, hat?: string | null) => boolean;
14
28
  /**
package/dist/stepup.js CHANGED
@@ -6,20 +6,29 @@ export const REMEMBER_PER = ['account', 'set', 'hat'];
6
6
  * together, so an entry written under `'account'` or `'set'` never matches it. A missing hat under `'hat'`, or a
7
7
  * value that isn't one of the three, has no key: nothing is remembered and nothing is written.
8
8
  */
9
- export const memoryKey = (opts, account, set, hat) => {
10
- const per = opts.stepUp?.rememberPer;
9
+ export const memoryKey = (opts, account, set, hat) => rememberKey(opts.stepUp?.rememberPer, { account, set, hat });
10
+ /**
11
+ * The same key as a pure function, for a site that reads `steppedUp` on a session itself (for example to check a code
12
+ * given for a wider hat). `per` is `stepUp.rememberPer` as the site set it. Returns `null` when there is no key.
13
+ */
14
+ export const rememberKey = (per, w) => {
11
15
  if (per === undefined || per === 'account')
12
- return account;
16
+ return w.account;
13
17
  if (per === 'set')
14
- return set ? `set:${set}` : account;
18
+ return w.set ? `set:${w.set}` : w.account;
15
19
  if (per === 'hat')
16
- return typeof hat === 'string' && hat ? `hat:${JSON.stringify([account, hat])}` : null;
20
+ return typeof w.hat === 'string' && w.hat ? `hat:${JSON.stringify([w.account, w.hat])}` : null;
17
21
  return null;
18
22
  };
23
+ /**
24
+ * When a code was given under `key`, as an ISO string, or `null` when it wasn't or `steppedUp` has no such entry.
25
+ * Reads own entries only. It does not check the age: compare it with `stepUp.rememberMinutes` (default 180).
26
+ */
27
+ export const rememberedAt = (steppedUp, key) => key === null || !steppedUp || !Object.hasOwn(steppedUp, key) ? null : typeof steppedUp[key] === 'string' ? steppedUp[key] : null;
19
28
  /** Whether a good code was given recently enough to count. */
20
29
  export const remembered = (opts, steppedUp, account, set, hat) => {
21
30
  const key = memoryKey(opts, account, set, hat);
22
- const at = key === null || !steppedUp || !Object.hasOwn(steppedUp, key) ? null : steppedUp[key];
31
+ const at = rememberedAt(steppedUp, key);
23
32
  return Boolean(at && Date.now() - new Date(at).getTime() < (opts.stepUp?.rememberMinutes ?? 180) * 60_000);
24
33
  };
25
34
  /**
package/dist/types.d.ts CHANGED
@@ -19,6 +19,22 @@ export type StepUpContext = {
19
19
  signedIn: HatsUser;
20
20
  /** The linked set's id, or null when the target account is in none. */
21
21
  set: string | null;
22
+ /** The hat being switched into. */
23
+ hat: string;
24
+ };
25
+ /**
26
+ * One line for the host's audit log, given to `audit` before the change it describes is committed. `actor` is the
27
+ * acting account (null when server code linked accounts with no vetter), `via` the account that session signed in
28
+ * with when it was switched, and `hat` the hat it wore.
29
+ */
30
+ export type AuditEntry = {
31
+ action: 'linked-trusted' | 'unlinked' | 'decoupled' | 'disabled';
32
+ actor: string | null;
33
+ account: string;
34
+ via: string | null;
35
+ hat: string | null;
36
+ reason: string | null;
37
+ req: PayloadRequest;
22
38
  };
23
39
  /** A user record as the plugin sees it. */
24
40
  export type HatsUser = TypedUser & {
@@ -75,6 +91,15 @@ export type HatsOptions = {
75
91
  * the same hat id on another account, linked or not. Any other value refuses to start.
76
92
  */
77
93
  rememberPer?: 'account' | 'set' | 'hat';
94
+ /**
95
+ * Called at the moment a switch is about to answer `needsCode` and no code came with the request, so a host that
96
+ * sends its code (by email, say) sends it exactly then. Never called when the hat is already worn, a code is
97
+ * remembered, or a code was given. If it throws, the switch is refused (`failed`, 500).
98
+ */
99
+ challenge?: (args: {
100
+ req: PayloadRequest;
101
+ user: HatsUser;
102
+ } & StepUpContext) => void | Promise<void>;
78
103
  };
79
104
  /**
80
105
  * Decides whether a switch needs a code, in place of the hat's `sensitive` flag. Called with the account and hat
@@ -108,8 +133,65 @@ export type HatsOptions = {
108
133
  /**
109
134
  * A reason switching, linking and unlinking are refused right now (e.g. "Stop masquerading first."), or null to go ahead.
110
135
  * Only null (or undefined) goes ahead: any other answer, and a throw, refuses with 409 `blocked`.
136
+ * The second argument names what is being asked for, so a host never has to work it out from the request's address.
137
+ * A hook that takes only `req` keeps working.
138
+ */
139
+ blocked?: (req: PayloadRequest, info: {
140
+ action: HatsAction;
141
+ }) => string | null | Promise<string | null>;
142
+ /**
143
+ * Whether an account may be in a linked set at all. Answer exactly true to allow it: any other answer, and a throw,
144
+ * is a no. Asked for both accounts when a link is requested, again when it is confirmed and approved, by
145
+ * `linkTrusted`, and before a switch into another account. Leaving a set is never asked. Default: every account may.
146
+ */
147
+ canBeLinked?: (args: {
148
+ req: PayloadRequest;
149
+ user: HatsUser;
150
+ }) => boolean | Promise<boolean>;
151
+ /**
152
+ * Who may control other people's accounts: list another account's set, take an account out of any set, dissolve a
153
+ * set, and disable accounts. Answer exactly true to allow it: any other answer, and a throw, is a no. It is a
154
+ * separate power from `canApproveLinks`. Default: nobody.
155
+ */
156
+ canControlAccounts?: (args: {
157
+ req: PayloadRequest;
158
+ user: HatsUser;
159
+ }) => boolean | Promise<boolean>;
160
+ /** What disabled means on the host. The plugin keeps no status of its own. */
161
+ disable?: {
162
+ /**
163
+ * Marks one account disabled, in the host's own field. Write with the `req` given, so the change joins the
164
+ * plugin's transaction. A throw refuses the call (`failed`, 500). Without it `disableAccount` and `disableAll`
165
+ * are refused (`disableOff`).
166
+ */
167
+ apply?: (args: {
168
+ req: PayloadRequest;
169
+ account: HatsUser;
170
+ reason: string | null;
171
+ }) => void | Promise<void>;
172
+ /**
173
+ * Reads an account's status back. Exactly `false` means the account is in use and exactly `true` means disabled.
174
+ * Any other answer, and a throw, is treated as disabled wherever that refuses something.
175
+ */
176
+ isDisabled: (user: HatsUser) => boolean | Promise<boolean>;
177
+ /**
178
+ * Accounts that are never disabled through the plugin. Answer exactly `false` to leave an account open to it:
179
+ * `true`, any other answer and a throw protect it, and a call that includes a protected account is refused whole.
180
+ * Default: no account is protected.
181
+ */
182
+ protect?: (args: {
183
+ req: PayloadRequest;
184
+ actor: HatsUser;
185
+ account: HatsUser;
186
+ }) => boolean | Promise<boolean>;
187
+ };
188
+ /**
189
+ * The host's audit log. Called once for each account a trusted link, an unlink, a decouple or a disable touches,
190
+ * after the writes and before they are committed, and awaited. If it throws, the call is refused (`auditFailed`,
191
+ * 500) and, where the database has transactions, undone. Write with the `req` given to join that transaction.
192
+ * `onEvent` is separate and stays best effort.
111
193
  */
112
- blocked?: (req: PayloadRequest) => string | null | Promise<string | null>;
194
+ audit?: (entry: AuditEntry) => void | Promise<void>;
113
195
  /**
114
196
  * Rate limit for link requests: answer exactly true to allow this one. Anything else, a throw included, refuses it
115
197
  * ("Too many link requests. Try again later.").
@@ -190,9 +272,51 @@ export type HatsEvent = {
190
272
  payload: Payload;
191
273
  sessions: number;
192
274
  reason: string;
275
+ } | {
276
+ type: 'decoupled';
277
+ payload: Payload;
278
+ link: string;
279
+ accounts: string[];
280
+ by: string;
281
+ } | {
282
+ type: 'accounts-disabled';
283
+ payload: Payload;
284
+ accounts: string[];
285
+ by: string;
286
+ reason: string | null;
287
+ } | {
288
+ type: 'linked-trusted';
289
+ payload: Payload;
290
+ link: string;
291
+ accounts: string[]; /** The account that vetted the link, or null for the host itself. */
292
+ by: string | null;
293
+ } | {
294
+ type: 'sign-in-account';
295
+ req: PayloadRequest;
296
+ /** The account the caller is acting as. */
297
+ from: string;
298
+ /** The linked account `accountToSignIn` answered for. */
299
+ account: string;
300
+ /** That account's own default hat, or null when it has no hats. */
301
+ hat: string | null;
302
+ /** The account the caller signed in with. */
303
+ via: string;
304
+ /** Whether that hat still needs a code. */
305
+ needsStepUp: boolean;
306
+ };
307
+ /** What a call to the host's `blocked` hook is about. */
308
+ export type HatsAction = 'list' | 'link' | 'confirm' | 'unlink' | 'decouple' | 'disable' | 'switch' | 'signIn';
309
+ /** A refusal from the linked-accounts API: a stable `reason`, the HTTP status a route would answer, and English words. */
310
+ export type Refusal = {
311
+ ok: false;
312
+ status: number;
313
+ reason: string;
314
+ message: string;
193
315
  };
194
- export type ResolvedHatsOptions = Required<Omit<HatsOptions, 'stepUp' | 'stepUpWhen' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL'>> & Pick<HatsOptions, 'stepUp' | 'stepUpWhen' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL'>;
316
+ type Optional = 'stepUp' | 'stepUpWhen' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL' | 'canBeLinked' | 'disable' | 'canControlAccounts' | 'audit';
317
+ export type ResolvedHatsOptions = Required<Omit<HatsOptions, Optional>> & Pick<HatsOptions, Optional>;
195
318
  export declare const LINKS = "hat-links";
196
319
  export declare const MEMBERS = "hat-members";
197
320
  export declare const SESSIONS = "hat-sessions";
198
321
  export declare const REQUESTS = "hat-requests";
322
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Linked accounts and role hats for Payload: one person switches between their approved accounts, and acts in one role at a time, with a second factor before switching up.",
5
5
  "keywords": [
6
6
  "payload",