@extantape/payload-plugin-hats 0.8.1 → 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/README.md +151 -4
- package/dist/accounts.d.ts +63 -0
- package/dist/accounts.js +403 -0
- package/dist/approval.d.ts +6 -0
- package/dist/approval.js +16 -0
- package/dist/collections.js +13 -2
- package/dist/endpoints.d.ts +34 -1
- package/dist/endpoints.js +263 -146
- package/dist/index.d.ts +49 -3
- package/dist/index.js +50 -1
- package/dist/link.d.ts +1 -1
- package/dist/link.js +19 -2
- package/dist/linking.d.ts +119 -0
- package/dist/linking.js +270 -0
- package/dist/sessions.js +8 -0
- package/dist/signin.d.ts +62 -0
- package/dist/signin.js +109 -0
- package/dist/state.d.ts +11 -1
- package/dist/state.js +26 -0
- package/dist/types.d.ts +126 -2
- package/package.json +1 -1
package/dist/endpoints.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
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 { runDecouple, runList, runUnlink } from './accounts.js';
|
|
5
|
+
import { checkLink, disabledState, mayBeLinked, overFull, setStands } from './linking.js';
|
|
4
6
|
import { cleanupSessions, isOffered, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
|
|
5
7
|
import { memoryKey, needsStepUp, remembered } from './stepup.js';
|
|
6
|
-
import { asPlugin, DISSOLVING, hashToken, hatsOptions, hatsStateOf, idOf, newToken, relId, removeWhere, tell, trackWork, unmarked, withMark } from './state.js';
|
|
8
|
+
import { asPlugin, DISSOLVING, hashToken, hatsOptions, hatsStateOf, idOf, newToken, relId, removeWhere, safeName, tell, trackWork, unmarked, withMark } from './state.js';
|
|
7
9
|
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
8
10
|
const json = (body, status = 200, cookies = []) => {
|
|
9
11
|
const headers = new Headers({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
@@ -12,22 +14,30 @@ const json = (body, status = 200, cookies = []) => {
|
|
|
12
14
|
return new Response(JSON.stringify(body), { status, headers });
|
|
13
15
|
};
|
|
14
16
|
/** A refusal with a stable `reason`, so a site can show its own words for it (the English message is the fallback). */
|
|
15
|
-
const refuse = (message, status = 403, reason) => {
|
|
17
|
+
export const refuse = (message, status = 403, reason) => {
|
|
16
18
|
throw new APIError(message, status, reason ? { reason } : undefined, true);
|
|
17
19
|
};
|
|
18
20
|
/** The acting account, its full record (all roles, not the hat), and the session's hat state. */
|
|
19
|
-
async function actor(req) {
|
|
21
|
+
export async function actor(req, noSession = 400, checkFirst = true) {
|
|
20
22
|
const opts = hatsOptions(req.payload);
|
|
21
23
|
const user = req.user;
|
|
22
24
|
if (!user || user.collection !== opts.users)
|
|
23
25
|
refuse('Sign in first.', 401, 'signIn');
|
|
24
26
|
const state = hatsStateOf(user);
|
|
25
27
|
if (!state)
|
|
26
|
-
refuse('Switching needs a browser sign-in.',
|
|
28
|
+
refuse('Switching needs a browser sign-in.', noSession, 'signIn');
|
|
27
29
|
const full = await loadUser(req, String(user.id));
|
|
28
30
|
if (!full)
|
|
29
31
|
refuse('Sign in first.', 401, 'signIn');
|
|
30
|
-
|
|
32
|
+
const person = state.via ?? String(user.id);
|
|
33
|
+
// A switched session answers for the person who first signed in, so one the host has since disabled or marked a minor
|
|
34
|
+
// gets nothing from the plugin's own endpoints. The switch and the sign-in read ask for themselves, so they pass false.
|
|
35
|
+
if (checkFirst && person !== String(user.id)) {
|
|
36
|
+
const first = await loadUser(req, person);
|
|
37
|
+
if (!first || (await disabledState(opts, req, first)) !== 'no' || !(await mayBeLinked(opts, req, first)))
|
|
38
|
+
refuse('That isn’t available for this account.', 403, 'notAvailable');
|
|
39
|
+
}
|
|
40
|
+
return { opts, user: user, full: full, state: state, person };
|
|
31
41
|
}
|
|
32
42
|
export const loadUser = async (req, id) => (await req.payload.findByID({ collection: hatsOptions(req.payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
|
|
33
43
|
export const labelOf = (u) => String(u.email ?? u.id);
|
|
@@ -69,10 +79,10 @@ export function showsSwitch(opts, args, worn) {
|
|
|
69
79
|
const own = args.hats.filter(isOffered).length + (args.hats.some((h) => h.id === worn && !isOffered(h)) ? 1 : 0);
|
|
70
80
|
return own > 1 || args.linked.some((l) => l.hats.filter(isOffered).length > 1);
|
|
71
81
|
}
|
|
72
|
-
async function blockedReason(req, opts) {
|
|
82
|
+
export async function blockedReason(req, opts, action) {
|
|
73
83
|
if (!opts.blocked)
|
|
74
84
|
return;
|
|
75
|
-
const why = await blockedBy(() => opts.blocked(req));
|
|
85
|
+
const why = await blockedBy(() => opts.blocked(req, { action }));
|
|
76
86
|
if (why !== null)
|
|
77
87
|
refuse(why, 409, 'blocked');
|
|
78
88
|
}
|
|
@@ -193,10 +203,23 @@ function refuseCrossSite(req) {
|
|
|
193
203
|
if (fetchSite != null && fetchSite !== 'same-origin')
|
|
194
204
|
refuse('Switching must come from this site.', 403, 'crossSite');
|
|
195
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* What Payload's own login would turn an account away for: a lock that hasn't run out, or an email not yet confirmed
|
|
208
|
+
* when the collection verifies emails. The switch and `accountToSignIn` both read it here, so they can't drift.
|
|
209
|
+
*/
|
|
210
|
+
export function loginBar(payload, opts, account) {
|
|
211
|
+
const lockUntil = account.lockUntil;
|
|
212
|
+
if (lockUntil != null && new Date(lockUntil).getTime() > Date.now())
|
|
213
|
+
return 'locked';
|
|
214
|
+
const auth = payload.collections[opts.users].config.auth;
|
|
215
|
+
if (auth.verify && account._verified === false)
|
|
216
|
+
return 'unverified';
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
196
219
|
async function switchCore(req, body) {
|
|
197
220
|
refuseCrossSite(req);
|
|
198
|
-
const { opts, full, state, person } = await actor(req);
|
|
199
|
-
await blockedReason(req, opts);
|
|
221
|
+
const { opts, full, state, person } = await actor(req, 400, false);
|
|
222
|
+
await blockedReason(req, opts, 'switch');
|
|
200
223
|
const current = String(full.id);
|
|
201
224
|
const to = body.account == null || body.account === '' ? current : String(body.account);
|
|
202
225
|
// Only an id exactly as the account has it. Anything else answers as an account that isn't linked, before any query.
|
|
@@ -211,14 +234,31 @@ async function switchCore(req, body) {
|
|
|
211
234
|
const target = to === current ? full : await loadUser(req, to);
|
|
212
235
|
if (!target)
|
|
213
236
|
refuse('That account isn’t linked to this one.', 403, 'notLinked');
|
|
214
|
-
// Direct login refuses a locked account, so a switch into one is refused too.
|
|
215
|
-
const
|
|
216
|
-
if (
|
|
237
|
+
// Direct login refuses a locked or unverified account, so a switch into one is refused too.
|
|
238
|
+
const bar = to === current ? null : loginBar(req.payload, opts, target);
|
|
239
|
+
if (bar === 'locked')
|
|
217
240
|
refuse('That account is locked. Try again later.', 403, 'locked');
|
|
218
|
-
|
|
219
|
-
const usersAuth = req.payload.collections[opts.users].config.auth;
|
|
220
|
-
if (to !== current && usersAuth.verify && target._verified === false)
|
|
241
|
+
if (bar === 'unverified')
|
|
221
242
|
refuse('That account’s email isn’t confirmed yet.', 403, 'unverified');
|
|
243
|
+
// An account the host calls disabled, or can't answer for, is never switched into, with or without a remembered code.
|
|
244
|
+
const off = async (account = target) => !account || (await disabledState(opts, req, account)) !== 'no';
|
|
245
|
+
if (await off())
|
|
246
|
+
refuse('That account is disabled.', 403, 'disabled');
|
|
247
|
+
// An account the host says can't be in a set can't be switched into either, whatever its row says.
|
|
248
|
+
// The same check covers the signed-in account, and a disabled one on either side, so a switch can't go where linking wouldn't.
|
|
249
|
+
if (to !== current || person !== current) {
|
|
250
|
+
// Whoever first signed in counts too: a person the host has since disabled can't keep moving between accounts,
|
|
251
|
+
// or changing hats inside the account they switched into.
|
|
252
|
+
const first = person === current ? null : await loadUser(req, person);
|
|
253
|
+
if (person !== current && !first)
|
|
254
|
+
refuse('Switching isn’t available for that account.', 403, 'notAvailable');
|
|
255
|
+
for (const who of first ? [first, full, target] : [full, target]) {
|
|
256
|
+
// Going back to the account the person first signed in with is the way out, so that account's own link rule doesn't apply to it.
|
|
257
|
+
const home = to === person && (who === first || who === target);
|
|
258
|
+
if ((await disabledState(opts, req, who)) !== 'no' || (!home && !(await mayBeLinked(opts, req, who))))
|
|
259
|
+
refuse('Switching isn’t available for that account.', 403, 'notAvailable');
|
|
260
|
+
}
|
|
261
|
+
}
|
|
222
262
|
const { linked } = await linkedAccounts(req, current);
|
|
223
263
|
const s = await sessionBySid(req.payload, state.sid, req);
|
|
224
264
|
const ownHats = opts.hatsOf(full);
|
|
@@ -243,12 +283,23 @@ async function switchCore(req, body) {
|
|
|
243
283
|
refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
|
|
244
284
|
// Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
|
|
245
285
|
const stepUp = opts.stepUp;
|
|
246
|
-
const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId };
|
|
286
|
+
const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId, hat: hat.id };
|
|
247
287
|
if (!(await exactlyTrue(() => stepUp.available(target, ctx))))
|
|
248
288
|
refuse('Set up two-step sign-in on that account first.', 403, 'setUpTwoStep');
|
|
249
289
|
const code = typeof body.code === 'string' ? body.code.trim() : '';
|
|
250
|
-
if (!code)
|
|
290
|
+
if (!code) {
|
|
291
|
+
// The one moment a code is needed and none came: a host that sends its code does it here.
|
|
292
|
+
if (typeof stepUp.challenge === 'function') {
|
|
293
|
+
try {
|
|
294
|
+
await unmarked(req, () => stepUp.challenge({ req, user: target, ...ctx }));
|
|
295
|
+
}
|
|
296
|
+
catch (error) {
|
|
297
|
+
req.payload.logger.error({ msg: `Hats: stepUp.challenge failed (${safeName(error)})` });
|
|
298
|
+
refuse('Switching didn’t work. Try again.', 500, 'failed');
|
|
299
|
+
}
|
|
300
|
+
}
|
|
251
301
|
return { ok: false, status: 401, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' };
|
|
302
|
+
}
|
|
252
303
|
if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
|
|
253
304
|
refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
|
|
254
305
|
const key = memoryKey(opts, to, setId, hat.id);
|
|
@@ -278,6 +329,12 @@ async function switchCore(req, body) {
|
|
|
278
329
|
overrideAccess: true,
|
|
279
330
|
req,
|
|
280
331
|
}));
|
|
332
|
+
// The account can be disabled between the check above and the session just made. Read again, and end the new
|
|
333
|
+
// session if so, so a switch and a disable at the same moment never leave a session behind.
|
|
334
|
+
if (await off(await loadUser(req, to))) {
|
|
335
|
+
await revokeSessions(req.payload, { sid: { equals: sid } }, 'account disabled', req);
|
|
336
|
+
refuse('That account is disabled.', 403, 'disabled');
|
|
337
|
+
}
|
|
281
338
|
await revokeSid(req.payload, current, state.sid, req);
|
|
282
339
|
if (s)
|
|
283
340
|
await tombstone(req.payload, s.id, req);
|
|
@@ -333,114 +390,144 @@ const pendingCap = (opts) => opts.maxLinked * 2;
|
|
|
333
390
|
*/
|
|
334
391
|
/** What a request's unique `holds` is: the account invited, or a value of its own that holds nothing. */
|
|
335
392
|
const holdFor = (account) => (account ? `account:${String(account.id)}` : `none:${newToken()}`);
|
|
393
|
+
/** Turns the refusals a core throws into a result, so the exported functions never throw for one. */
|
|
394
|
+
export async function asResult(req, what, run) {
|
|
395
|
+
try {
|
|
396
|
+
return await run();
|
|
397
|
+
}
|
|
398
|
+
catch (error) {
|
|
399
|
+
if (error instanceof APIError) {
|
|
400
|
+
const reason = error.data?.reason;
|
|
401
|
+
return { ok: false, status: error.status, reason: typeof reason === 'string' ? reason : 'failed', message: error.message };
|
|
402
|
+
}
|
|
403
|
+
req.payload?.logger?.warn({ err: error }, `Hats: ${what} refused after an unexpected error`);
|
|
404
|
+
return { ok: false, status: 500, reason: 'failed', message: 'That didn’t work. Try again.' };
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* The one link request, shared by POST /api/hats/link and `requestLink`. It acts only for `req.user`, has no option
|
|
409
|
+
* that skips a check, and never throws for a refusal.
|
|
410
|
+
*/
|
|
411
|
+
export const runRequestLink = (req, input) => asResult(req, 'a link request', () => linkCore(req, input ?? {}));
|
|
412
|
+
async function linkCore(req, input) {
|
|
413
|
+
const { opts, full } = await actor(req, 401);
|
|
414
|
+
await blockedReason(req, opts, 'link');
|
|
415
|
+
if (!opts.canApproveLinks)
|
|
416
|
+
refuse('Linking accounts isn’t turned on here.', 403, 'linkingOff');
|
|
417
|
+
const email = String(typeof input.email === 'string' ? input.email : '').trim().toLowerCase();
|
|
418
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
419
|
+
refuse('Enter the other account’s email address.', 400, 'enterEmail');
|
|
420
|
+
// Refused unless the site's limit answers exactly true (a throw, false or any other answer is a no): nothing is recorded or sent.
|
|
421
|
+
if (opts.limit && !(await exactlyTrue(() => opts.limit({ req, user: full, email }))))
|
|
422
|
+
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
423
|
+
const me = String(full.id);
|
|
424
|
+
const now = new Date();
|
|
425
|
+
// Everything up to here depends only on the asker and what they typed. From here on the answer waits for the
|
|
426
|
+
// same fixed time whatever happens, so how long the work takes says nothing about the address.
|
|
427
|
+
const answer = new Promise((resolve) => setTimeout(resolve, opts.linkAnswerMs));
|
|
428
|
+
await asPlugin(req, async () => {
|
|
429
|
+
// Requests nobody confirmed in time don't hold anyone up.
|
|
430
|
+
// Best effort: what isn't removed now goes on a later request, and the request goes on either way.
|
|
431
|
+
for (const swept of [
|
|
432
|
+
await req.payload.delete({ collection: MEMBERS, where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] }, overrideAccess: true, showHiddenFields: true, req }),
|
|
433
|
+
await req.payload.delete({ collection: REQUESTS, where: { expiresAt: { less_than: now.toISOString() } }, overrideAccess: true, req }),
|
|
434
|
+
])
|
|
435
|
+
if (swept.errors?.length)
|
|
436
|
+
req.payload.logger.warn({ msg: 'Hats: some expired link requests were not removed; a later request retries' });
|
|
437
|
+
});
|
|
438
|
+
const mine = await membershipOf(req, me);
|
|
439
|
+
const set = mine ? idOf(mine.link) : null;
|
|
440
|
+
// The asker's side of the shared check, with one seat kept for the account they named. It depends only on the
|
|
441
|
+
// asker, so its answer says nothing about the address.
|
|
442
|
+
const own = await checkLink(req.payload, opts, { req, set, members: mine ? [full] : [], joining: mine ? [] : [full], slots: 1 });
|
|
443
|
+
if (!own.ok) {
|
|
444
|
+
await answer;
|
|
445
|
+
refuse(own.message, own.status, own.reason);
|
|
446
|
+
}
|
|
447
|
+
const open = await req.payload.count({ collection: REQUESTS, where: { requestedBy: { equals: me } }, overrideAccess: true, req });
|
|
448
|
+
if (open.totalDocs >= pendingCap(opts)) {
|
|
449
|
+
await answer;
|
|
450
|
+
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
451
|
+
}
|
|
452
|
+
const work = async () => {
|
|
453
|
+
const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
454
|
+
const found = docs[0];
|
|
455
|
+
// The whole shared check, now with the account named: one that is already linked, disabled or not allowed in a
|
|
456
|
+
// set gets no invitation, and the asker sees what they see for any address.
|
|
457
|
+
let target = found && String(found.id) !== me && (await checkLink(req.payload, opts, { req, set, members: mine ? [full] : [], joining: mine ? [found] : [full, found] })).ok ? found : null;
|
|
458
|
+
// One record for every request, with the same fields. Only a real invitation's token can ever be used.
|
|
459
|
+
const token = newToken();
|
|
460
|
+
const hours = opts.confirmHours;
|
|
461
|
+
const hold = holdFor(null);
|
|
462
|
+
const request = (await asPlugin(req, () => req.payload.create({
|
|
463
|
+
collection: REQUESTS,
|
|
464
|
+
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 },
|
|
465
|
+
overrideAccess: true,
|
|
466
|
+
req,
|
|
467
|
+
})));
|
|
468
|
+
// The asker's own note is the same every time and leaves the address out, so it can't tell them anything. It
|
|
469
|
+
// goes before anything that depends on the address (looking it up, checking its set, claiming it), so the
|
|
470
|
+
// work done before it, and when it arrives, is the same for a real address and a made-up one.
|
|
471
|
+
try {
|
|
472
|
+
await opts.sendEmail({
|
|
473
|
+
payload: req.payload,
|
|
474
|
+
to: String(full.email),
|
|
475
|
+
subject: 'You asked to link an account',
|
|
476
|
+
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.`,
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
catch (err) {
|
|
480
|
+
req.payload.logger.warn({ err }, 'Hats: link request note not sent');
|
|
481
|
+
}
|
|
482
|
+
// One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
|
|
483
|
+
// rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
|
|
484
|
+
// the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
|
|
485
|
+
// means no invitation, so the asker sees the same thing either way.
|
|
486
|
+
const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
|
|
487
|
+
const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
|
|
488
|
+
if (!claimed)
|
|
489
|
+
target = null;
|
|
490
|
+
if (!target)
|
|
491
|
+
return;
|
|
492
|
+
try {
|
|
493
|
+
await opts.sendEmail({
|
|
494
|
+
payload: req.payload,
|
|
495
|
+
to: String(target.email),
|
|
496
|
+
subject: 'Confirm linking your accounts',
|
|
497
|
+
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.`,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
catch (err) {
|
|
501
|
+
// The invitation never arrived, so its token must never work.
|
|
502
|
+
req.payload.logger.warn({ err }, 'Hats: link invitation not sent');
|
|
503
|
+
await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: { account: null, holds: holdFor(null), tokenHash: null }, overrideAccess: true, req }));
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
// With no set yet, the event waits for confirmation, when the set exists, so `link` is always a real set.
|
|
507
|
+
if (mine)
|
|
508
|
+
await tell(req.payload, req, { type: 'link-requested', req, link: idOf(mine.link), by: me, account: String(target.id) });
|
|
509
|
+
};
|
|
510
|
+
let finished = false;
|
|
511
|
+
const done = work()
|
|
512
|
+
.catch((err) => req.payload.logger.warn({ err }, 'Hats: link request not finished'))
|
|
513
|
+
.finally(() => {
|
|
514
|
+
finished = true;
|
|
515
|
+
});
|
|
516
|
+
trackWork(done);
|
|
517
|
+
await answer;
|
|
518
|
+
if (!finished)
|
|
519
|
+
void done.then(() => req.payload.logger.info('Hats: a link request finished after its answer. Raise linkAnswerMs if this repeats.'));
|
|
520
|
+
return { ok: true, reason: 'linkSent', message: SENT };
|
|
521
|
+
}
|
|
336
522
|
const requestLink = {
|
|
337
523
|
path: '/hats/link',
|
|
338
524
|
method: 'post',
|
|
339
525
|
handler: async (req) => {
|
|
340
526
|
await addDataAndFileToRequest(req);
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
const email = String(req.data?.email ?? '').trim().toLowerCase();
|
|
346
|
-
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
347
|
-
refuse('Enter the other account’s email address.', 400, 'enterEmail');
|
|
348
|
-
// Refused unless the site's limit answers exactly true (a throw, false or any other answer is a no): nothing is recorded or sent.
|
|
349
|
-
if (opts.limit && !(await exactlyTrue(() => opts.limit({ req, user: full, email }))))
|
|
350
|
-
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
351
|
-
const me = String(full.id);
|
|
352
|
-
const now = new Date();
|
|
353
|
-
// Everything up to here depends only on the asker and what they typed. From here on the answer waits for the
|
|
354
|
-
// same fixed time whatever happens, so how long the work takes says nothing about the address.
|
|
355
|
-
const answer = new Promise((resolve) => setTimeout(resolve, opts.linkAnswerMs));
|
|
356
|
-
await asPlugin(req, async () => {
|
|
357
|
-
// Requests nobody confirmed in time don't hold anyone up.
|
|
358
|
-
// Best effort: what isn't removed now goes on a later request, and the request goes on either way.
|
|
359
|
-
for (const swept of [
|
|
360
|
-
await req.payload.delete({ collection: MEMBERS, where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] }, overrideAccess: true, showHiddenFields: true, req }),
|
|
361
|
-
await req.payload.delete({ collection: REQUESTS, where: { expiresAt: { less_than: now.toISOString() } }, overrideAccess: true, req }),
|
|
362
|
-
])
|
|
363
|
-
if (swept.errors?.length)
|
|
364
|
-
req.payload.logger.warn({ msg: 'Hats: some expired link requests were not removed; a later request retries' });
|
|
365
|
-
});
|
|
366
|
-
const mine = await membershipOf(req, me);
|
|
367
|
-
const already = mine ? (await members(req, idOf(mine.link))).length : 0;
|
|
368
|
-
if (already + (mine ? 1 : 2) > opts.maxLinked) {
|
|
369
|
-
await answer;
|
|
370
|
-
refuse(`A set can hold at most ${opts.maxLinked} accounts.`, 400, 'setFull');
|
|
371
|
-
}
|
|
372
|
-
const open = await req.payload.count({ collection: REQUESTS, where: { requestedBy: { equals: me } }, overrideAccess: true, req });
|
|
373
|
-
if (open.totalDocs >= pendingCap(opts)) {
|
|
374
|
-
await answer;
|
|
375
|
-
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
376
|
-
}
|
|
377
|
-
const work = async () => {
|
|
378
|
-
// One record for every request, with the same fields. Only a real invitation's token can ever be used.
|
|
379
|
-
const token = newToken();
|
|
380
|
-
const hours = opts.confirmHours;
|
|
381
|
-
const hold = holdFor(null);
|
|
382
|
-
const request = (await asPlugin(req, () => req.payload.create({
|
|
383
|
-
collection: REQUESTS,
|
|
384
|
-
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 },
|
|
385
|
-
overrideAccess: true,
|
|
386
|
-
req,
|
|
387
|
-
})));
|
|
388
|
-
// The asker's own note is the same every time and leaves the address out, so it can't tell them anything. It
|
|
389
|
-
// goes before anything that depends on the address (looking it up, checking its set, claiming it), so the
|
|
390
|
-
// work done before it, and when it arrives, is the same for a real address and a made-up one.
|
|
391
|
-
try {
|
|
392
|
-
await opts.sendEmail({
|
|
393
|
-
payload: req.payload,
|
|
394
|
-
to: String(full.email),
|
|
395
|
-
subject: 'You asked to link an account',
|
|
396
|
-
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.`,
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
catch (err) {
|
|
400
|
-
req.payload.logger.warn({ err }, 'Hats: link request note not sent');
|
|
401
|
-
}
|
|
402
|
-
const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
403
|
-
const found = docs[0];
|
|
404
|
-
let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
|
|
405
|
-
// One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
|
|
406
|
-
// rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
|
|
407
|
-
// the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
|
|
408
|
-
// means no invitation, so the asker sees the same thing either way.
|
|
409
|
-
const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
|
|
410
|
-
const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
|
|
411
|
-
if (!claimed)
|
|
412
|
-
target = null;
|
|
413
|
-
if (!target)
|
|
414
|
-
return;
|
|
415
|
-
try {
|
|
416
|
-
await opts.sendEmail({
|
|
417
|
-
payload: req.payload,
|
|
418
|
-
to: String(target.email),
|
|
419
|
-
subject: 'Confirm linking your accounts',
|
|
420
|
-
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.`,
|
|
421
|
-
});
|
|
422
|
-
}
|
|
423
|
-
catch (err) {
|
|
424
|
-
// The invitation never arrived, so its token must never work.
|
|
425
|
-
req.payload.logger.warn({ err }, 'Hats: link invitation not sent');
|
|
426
|
-
await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: { account: null, holds: holdFor(null), tokenHash: null }, overrideAccess: true, req }));
|
|
427
|
-
return;
|
|
428
|
-
}
|
|
429
|
-
// With no set yet, the event waits for confirmation, when the set exists, so `link` is always a real set.
|
|
430
|
-
if (mine)
|
|
431
|
-
await tell(req.payload, req, { type: 'link-requested', req, link: idOf(mine.link), by: me, account: String(target.id) });
|
|
432
|
-
};
|
|
433
|
-
let finished = false;
|
|
434
|
-
const done = work()
|
|
435
|
-
.catch((err) => req.payload.logger.warn({ err }, 'Hats: link request not finished'))
|
|
436
|
-
.finally(() => {
|
|
437
|
-
finished = true;
|
|
438
|
-
});
|
|
439
|
-
trackWork(done);
|
|
440
|
-
await answer;
|
|
441
|
-
if (!finished)
|
|
442
|
-
void done.then(() => req.payload.logger.info('Hats: a link request finished after its answer. Raise linkAnswerMs if this repeats.'));
|
|
443
|
-
return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
|
|
527
|
+
const result = await runRequestLink(req, (req.data ?? {}));
|
|
528
|
+
if (result.ok)
|
|
529
|
+
return json(result, 202);
|
|
530
|
+
return refuse(result.message, result.status, result.reason);
|
|
444
531
|
},
|
|
445
532
|
};
|
|
446
533
|
const page = (title, body, status = 200) => new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${title}</title><style>body{font:1rem/1.5 system-ui,sans-serif;max-width:36rem;margin:4rem auto;padding:0 1rem;color:#222;background:#fff}button{font:inherit;padding:.6rem 1.2rem;border-radius:.4rem;border:1px solid #333;background:#222;color:#fff;cursor:pointer}button:focus-visible{outline:3px solid #c60;outline-offset:2px}@media (prefers-color-scheme:dark){body{color:#eee;background:#111}button{background:#eee;color:#111;border-color:#eee}}</style></head><body><main><h1>${title}</h1>${body}</main></body></html>`, { status, headers: { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' } });
|
|
@@ -471,6 +558,10 @@ const confirm = {
|
|
|
471
558
|
if (!token)
|
|
472
559
|
return bad();
|
|
473
560
|
const opts = hatsOptions(req.payload);
|
|
561
|
+
// A confirmation is a write, so the host's `blocked` is asked. A refusal leaves the token unused.
|
|
562
|
+
const why = opts.blocked ? await blockedBy(() => opts.blocked(req, { action: 'confirm' })) : null;
|
|
563
|
+
if (why !== null)
|
|
564
|
+
return page('Not right now', `<p>${esc(why)}</p>`, 409);
|
|
474
565
|
const hash = hashToken(token);
|
|
475
566
|
const thanks = () => page('Confirmed', '<p>Thanks. Once every account in the link is confirmed, an administrator reviews it. You can close this page.</p>');
|
|
476
567
|
// The asker confirming their own side, after the other account confirmed.
|
|
@@ -479,9 +570,15 @@ const confirm = {
|
|
|
479
570
|
if (m) {
|
|
480
571
|
if (m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
|
|
481
572
|
return bad();
|
|
482
|
-
|
|
573
|
+
const self = await loadUser(req, idOf(m.user));
|
|
574
|
+
if (!self || !(await checkLink(req.payload, opts, { req, set: idOf(m.link), members: [self], joining: [] })).ok)
|
|
483
575
|
return bad();
|
|
484
|
-
|
|
576
|
+
try {
|
|
577
|
+
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 }));
|
|
578
|
+
}
|
|
579
|
+
catch {
|
|
580
|
+
return bad(); // the row went a moment ago: the set was dissolved or the account taken out
|
|
581
|
+
}
|
|
485
582
|
await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: idOf(m.link), account: idOf(m.user) });
|
|
486
583
|
return thanks();
|
|
487
584
|
}
|
|
@@ -505,7 +602,7 @@ const confirm = {
|
|
|
505
602
|
return bad();
|
|
506
603
|
const asker = await loadUser(req, by);
|
|
507
604
|
const invited = await loadUser(req, account);
|
|
508
|
-
if (!asker || !invited
|
|
605
|
+
if (!asker || !invited)
|
|
509
606
|
return bad();
|
|
510
607
|
const mine = await membershipOf(req, by);
|
|
511
608
|
const existing = mine ? idOf(mine.link) : null;
|
|
@@ -517,7 +614,8 @@ const confirm = {
|
|
|
517
614
|
if (!started || idOf(started.requestedBy) !== by)
|
|
518
615
|
return bad();
|
|
519
616
|
}
|
|
520
|
-
|
|
617
|
+
// The shared check again, on what is true now: either account may have been linked, disabled or ruled out since.
|
|
618
|
+
if (!(await checkLink(req.payload, opts, { req, set: existing, members: mine ? [asker] : [], joining: mine ? [invited] : [asker, invited] })).ok)
|
|
521
619
|
return bad();
|
|
522
620
|
const made = { rows: [] };
|
|
523
621
|
try {
|
|
@@ -547,6 +645,14 @@ const confirm = {
|
|
|
547
645
|
made.own = own;
|
|
548
646
|
}
|
|
549
647
|
});
|
|
648
|
+
// Two confirmations into one set can both pass the check a moment apart. Each reads the set again after its
|
|
649
|
+
// write and takes its own rows back if the set is over the limit.
|
|
650
|
+
if (await overFull(req.payload, opts, existing ?? made.link, req))
|
|
651
|
+
throw new Error('Hats: the set filled up while this confirmation was being written');
|
|
652
|
+
// The asker's set can be dissolved, or the asker taken out of it, between the check and the write. Then the
|
|
653
|
+
// row just written hangs on nothing, and it is taken back.
|
|
654
|
+
if (!(await setStands(req.payload, existing ?? made.link, mine ? by : null, req)))
|
|
655
|
+
throw new Error('Hats: the set was dissolved while this confirmation was being written');
|
|
550
656
|
// The site's own callbacks run after the plugin's writes, with its mark off the request.
|
|
551
657
|
if (made.own) {
|
|
552
658
|
const own = made.own;
|
|
@@ -587,33 +693,44 @@ export function exactId(req, opts, v) {
|
|
|
587
693
|
return /^(0|-?[1-9]\d{0,15})$/.test(s) && Number.isSafeInteger(Number(s));
|
|
588
694
|
return typeof v === 'string' && s.length > 0 && s.length <= 256 && s.trim() === s;
|
|
589
695
|
}
|
|
590
|
-
/**
|
|
696
|
+
/**
|
|
697
|
+
* POST /api/hats/unlink { account? }: take an account (default: the acting one) out of the set. Self-serve, at once.
|
|
698
|
+
* Taking another account out needs an approved account in the same set, or any account in it while nobody is
|
|
699
|
+
* approved yet, or a controller.
|
|
700
|
+
*/
|
|
591
701
|
const unlink = {
|
|
592
702
|
path: '/hats/unlink',
|
|
593
703
|
method: 'post',
|
|
594
704
|
handler: async (req) => {
|
|
595
705
|
await addDataAndFileToRequest(req);
|
|
596
|
-
const
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
const
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
706
|
+
const result = await runUnlink(req, (req.data ?? {}));
|
|
707
|
+
if (result.ok)
|
|
708
|
+
return json(result);
|
|
709
|
+
return refuse(result.message, result.status, result.reason);
|
|
710
|
+
},
|
|
711
|
+
};
|
|
712
|
+
/** GET /api/hats/accounts[?of=<account>]: the acting account's linked accounts, or another account's for a controller. */
|
|
713
|
+
const accounts = {
|
|
714
|
+
path: '/hats/accounts',
|
|
715
|
+
method: 'get',
|
|
716
|
+
handler: async (req) => {
|
|
717
|
+
const result = await runList(req, { of: new URL(req.url ?? 'http://localhost').searchParams.get('of') });
|
|
718
|
+
if (result.ok)
|
|
719
|
+
return json(result);
|
|
720
|
+
return refuse(result.message, result.status, result.reason);
|
|
721
|
+
},
|
|
722
|
+
};
|
|
723
|
+
/** POST /api/hats/decouple { account? }: dissolve the whole set that account (default: the acting one) is in. Every account stays whole. */
|
|
724
|
+
const decouple = {
|
|
725
|
+
path: '/hats/decouple',
|
|
726
|
+
method: 'post',
|
|
727
|
+
handler: async (req) => {
|
|
728
|
+
await addDataAndFileToRequest(req);
|
|
729
|
+
const result = await runDecouple(req, (req.data ?? {}));
|
|
730
|
+
if (result.ok)
|
|
731
|
+
return json(result);
|
|
732
|
+
return refuse(result.message, result.status, result.reason);
|
|
616
733
|
},
|
|
617
734
|
};
|
|
618
|
-
export const hatEndpoints = [me, switchHat, requestLink, confirmPage, confirm, unlink];
|
|
735
|
+
export const hatEndpoints = [me, switchHat, requestLink, confirmPage, confirm, unlink, accounts, decouple];
|
|
619
736
|
export { revokeSessions };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import type { PayloadRequest, Plugin } from 'payload';
|
|
2
|
-
import { type
|
|
2
|
+
import { type DecoupleResult, type DisableInput, type DisableResult, type LinkedAccount, type LinkedAccountsResult, type UnlinkResult } from './accounts.js';
|
|
3
|
+
import { type LinkRequestResult, type SwitchInput, type SwitchResult } from './endpoints.js';
|
|
3
4
|
import { type HatsOptions } from './types.js';
|
|
4
5
|
export { hatsStateOf } from './state.js';
|
|
5
6
|
export { rememberKey, rememberedAt } from './stepup.js';
|
|
6
7
|
export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
|
|
7
8
|
export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
8
|
-
export
|
|
9
|
+
export { getLinkedSet, HatsRefusal, linkTrusted } from './linking.js';
|
|
10
|
+
export type { LinkedSet, LinkTrustedInput, LinkTrustedResult } from './linking.js';
|
|
11
|
+
export { accountToSignIn, signInAnswer } from './signin.js';
|
|
12
|
+
export type { AccountToSignInOptions, AccountToSignInResult, SignInAnswer } from './signin.js';
|
|
13
|
+
export type { DecoupleResult, DisableInput, DisableResult, LinkedAccount, LinkedAccountsResult, LinkRequestResult, SwitchInput, SwitchResult, UnlinkResult };
|
|
9
14
|
export { approveLink, checkLinks, linkAccounts } from './link.js';
|
|
10
15
|
export type { ApproveInput, LinkCheck, LinkInput, LinkProblem, LinkReason, LinkResult, LinkRowStatus } from './link.js';
|
|
11
16
|
/**
|
|
@@ -22,5 +27,46 @@ export declare const switchSession: (req: PayloadRequest, input: {
|
|
|
22
27
|
hat?: string;
|
|
23
28
|
code?: string;
|
|
24
29
|
}) => Promise<SwitchResult>;
|
|
25
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Ask to link the signed-in account with the account at `email`, from a site's own route. It runs the same code as
|
|
32
|
+
* `POST /api/hats/link`, the fixed answer time included, and has no option that skips a check. It acts only for
|
|
33
|
+
* `req.user` and never throws for a refusal. `{ ok: true }` means the request was taken, whatever the address: a
|
|
34
|
+
* route should answer 202 with the same words every time.
|
|
35
|
+
*/
|
|
36
|
+
export declare const requestLink: (req: PayloadRequest, input: {
|
|
37
|
+
email: string;
|
|
38
|
+
}) => Promise<LinkRequestResult>;
|
|
39
|
+
/**
|
|
40
|
+
* The linked accounts of the signed-in account, as it may see them: itself and the approved accounts. An account
|
|
41
|
+
* still waiting is left out. Listing your own set is always open, in a read-only session too. With `of`, a controller
|
|
42
|
+
* (`canControlAccounts`) reads another account's set, every row with its status. It acts only for `req.user`.
|
|
43
|
+
*/
|
|
44
|
+
export declare const listLinkedAccounts: (req: PayloadRequest, input?: {
|
|
45
|
+
of?: string | number;
|
|
46
|
+
}) => Promise<LinkedAccountsResult>;
|
|
47
|
+
/**
|
|
48
|
+
* Take one account out of its set, from a site's own route. It runs the same code as `POST /api/hats/unlink`. Your
|
|
49
|
+
* own account can always leave. Another account needs an approved account in the same set, or any account in it
|
|
50
|
+
* while nobody is approved yet, or a controller. It acts only for `req.user` and never throws for a refusal.
|
|
51
|
+
*/
|
|
52
|
+
export declare const unlinkAccount: (req: PayloadRequest, input?: {
|
|
53
|
+
account?: string | number;
|
|
54
|
+
}) => Promise<UnlinkResult>;
|
|
55
|
+
/**
|
|
56
|
+
* Dissolve the whole set an account is in (default: the signed-in account's). Every account stays whole, and every
|
|
57
|
+
* session switched through the set ends. For an approved account in that set, or a controller. It runs the same code
|
|
58
|
+
* as `POST /api/hats/decouple`, acts only for `req.user` and never throws for a refusal.
|
|
59
|
+
*/
|
|
60
|
+
export declare const decouple: (req: PayloadRequest, input?: {
|
|
61
|
+
account?: string | number;
|
|
62
|
+
}) => Promise<DecoupleResult>;
|
|
63
|
+
/**
|
|
64
|
+
* Disable one account, through the host's `disable.apply`. For a controller only, and never the account the caller
|
|
65
|
+
* is signed in with or a protected one. The plugin adds no endpoint for it: call it from your own admin route.
|
|
66
|
+
* `dryRun: true` runs every check and writes nothing. It acts only for `req.user` and never throws for a refusal.
|
|
67
|
+
*/
|
|
68
|
+
export declare const disableAccount: (req: PayloadRequest, input: DisableInput) => Promise<DisableResult>;
|
|
69
|
+
/** Disable every approved account in `account`'s set, with the same rules as `disableAccount`. An account still waiting in the set is never touched. */
|
|
70
|
+
export declare const disableAll: (req: PayloadRequest, input: DisableInput) => Promise<DisableResult>;
|
|
71
|
+
export type { AuditEntry, Hat, HatsAction, HatsEvent, HatsOptions, HatsState, HatsUser, LinkSource, Refusal, StepUpContext } from './types.js';
|
|
26
72
|
export declare const hats: (options: HatsOptions) => Plugin;
|