@extantape/payload-plugin-hats 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +78 -2
- package/dist/access.d.ts +13 -0
- package/dist/access.js +30 -0
- package/dist/client/HatSwitcher.d.ts +10 -0
- package/dist/client/HatSwitcher.js +101 -0
- package/dist/client/LinkedAccounts.d.ts +10 -0
- package/dist/client/LinkedAccounts.js +59 -0
- package/dist/client/api.d.ts +95 -0
- package/dist/client/api.js +62 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +4 -0
- package/dist/collections.d.ts +3 -0
- package/dist/collections.js +131 -0
- package/dist/endpoints.d.ts +4 -0
- package/dist/endpoints.js +345 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +81 -0
- package/dist/sessions.d.ts +44 -0
- package/dist/sessions.js +162 -0
- package/dist/state.d.ts +13 -0
- package/dist/state.js +29 -0
- package/dist/stepup.d.ts +21 -0
- package/dist/stepup.js +26 -0
- package/dist/types.d.ts +175 -0
- package/dist/types.js +3 -0
- package/package.json +72 -4
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { exactlyTrue } from './access.js';
|
|
3
|
+
import { dissolveIfAlone, revokeSessions } from './sessions.js';
|
|
4
|
+
import { hatsStateOf, idOf } from './state.js';
|
|
5
|
+
import { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
6
|
+
const internal = (req) => req.context?.hatsInternal === true;
|
|
7
|
+
/**
|
|
8
|
+
* Whether the request's user may approve links. A person never approves their own link: an approver who is (or
|
|
9
|
+
* who signed in as) a member of the set is refused, so the owner's own links need another approver. Only an exact
|
|
10
|
+
* `true` from `canApproveLinks` counts: a truthy value or a thrown error is a no.
|
|
11
|
+
*/
|
|
12
|
+
async function approver(opts, req) {
|
|
13
|
+
const user = req.user;
|
|
14
|
+
if (!user || user.collection !== opts.users || !opts.canApproveLinks)
|
|
15
|
+
return false;
|
|
16
|
+
const ask = opts.canApproveLinks;
|
|
17
|
+
return exactlyTrue(() => ask({ req, user }));
|
|
18
|
+
}
|
|
19
|
+
export function hatCollections(opts) {
|
|
20
|
+
const canApprove = ({ req }) => approver(opts, req);
|
|
21
|
+
const never = () => false;
|
|
22
|
+
const links = {
|
|
23
|
+
slug: LINKS,
|
|
24
|
+
labels: { singular: 'Linked set', plural: 'Linked sets' },
|
|
25
|
+
admin: { hidden: true, group: 'Accounts', useAsTitle: 'label' },
|
|
26
|
+
access: { read: canApprove, create: never, update: never, delete: never },
|
|
27
|
+
fields: [
|
|
28
|
+
// What approvers see where a row names its set: "Started by someone@example.com".
|
|
29
|
+
{ name: 'label', type: 'text', admin: { readOnly: true } },
|
|
30
|
+
{ name: 'requestedBy', type: 'relationship', relationTo: opts.users, admin: { readOnly: true } },
|
|
31
|
+
],
|
|
32
|
+
};
|
|
33
|
+
const members = {
|
|
34
|
+
slug: MEMBERS,
|
|
35
|
+
labels: { singular: 'Linked account', plural: 'Linked accounts' },
|
|
36
|
+
admin: {
|
|
37
|
+
group: 'Accounts',
|
|
38
|
+
defaultColumns: ['user', 'status', 'link', 'confirmedAt', 'approvedAt'],
|
|
39
|
+
description: 'Accounts that one person asked to link. Approve a confirmed one by setting its status to Approved. You can’t approve a set you belong to. Delete a row to unlink it.',
|
|
40
|
+
},
|
|
41
|
+
access: { read: canApprove, create: never, update: canApprove, delete: canApprove },
|
|
42
|
+
fields: [
|
|
43
|
+
{ name: 'link', type: 'relationship', relationTo: LINKS, required: true, index: true, label: 'Linked set', admin: { readOnly: true, description: 'Filter the list by this set to see every account in it.' } },
|
|
44
|
+
{ name: 'user', type: 'relationship', relationTo: opts.users, required: true, unique: true, admin: { readOnly: true } },
|
|
45
|
+
{
|
|
46
|
+
name: 'status',
|
|
47
|
+
type: 'select',
|
|
48
|
+
required: true,
|
|
49
|
+
defaultValue: 'requested',
|
|
50
|
+
options: [
|
|
51
|
+
{ label: 'Waiting for the email to be confirmed', value: 'requested' },
|
|
52
|
+
{ label: 'Confirmed, waiting for approval', value: 'confirmed' },
|
|
53
|
+
{ label: 'Approved', value: 'approved' },
|
|
54
|
+
],
|
|
55
|
+
},
|
|
56
|
+
{ name: 'tokenHash', type: 'text', index: true, hidden: true },
|
|
57
|
+
{ name: 'tokenExpires', type: 'date', hidden: true },
|
|
58
|
+
{ name: 'addedBy', type: 'relationship', relationTo: opts.users, admin: { readOnly: true } },
|
|
59
|
+
{ name: 'confirmedAt', type: 'date', admin: { readOnly: true } },
|
|
60
|
+
{ name: 'approvedBy', type: 'relationship', relationTo: opts.users, admin: { readOnly: true } },
|
|
61
|
+
{ name: 'approvedAt', type: 'date', admin: { readOnly: true } },
|
|
62
|
+
],
|
|
63
|
+
hooks: {
|
|
64
|
+
beforeChange: [
|
|
65
|
+
async ({ data, originalDoc, operation, req }) => {
|
|
66
|
+
if (internal(req))
|
|
67
|
+
return data;
|
|
68
|
+
// Outside the plugin's own endpoints, the only change allowed is an approver approving a confirmed account.
|
|
69
|
+
if (operation !== 'update' || !originalDoc)
|
|
70
|
+
throw new APIError('Links are requested from the account page.', 403, undefined, true);
|
|
71
|
+
if (!(await approver(opts, req)))
|
|
72
|
+
throw new APIError('You can’t approve links.', 403, undefined, true);
|
|
73
|
+
const fields = ['link', 'user', 'tokenHash', 'tokenExpires', 'addedBy', 'confirmedAt', 'approvedBy', 'approvedAt'];
|
|
74
|
+
for (const f of fields)
|
|
75
|
+
if (f in data && data[f] !== undefined && String(idOf(data[f] ?? null)) !== String(idOf(originalDoc[f] ?? null)))
|
|
76
|
+
throw new APIError('Only the status can be changed here.', 403, undefined, true);
|
|
77
|
+
if (data.status === originalDoc.status)
|
|
78
|
+
return data;
|
|
79
|
+
if (originalDoc.status !== 'confirmed' || data.status !== 'approved')
|
|
80
|
+
throw new APIError('Only a confirmed account can be approved, and an approval can’t be undone here: delete the row to unlink.', 400, undefined, true);
|
|
81
|
+
const me = req.user;
|
|
82
|
+
const people = [String(me.id), hatsStateOf(me)?.via].filter(Boolean);
|
|
83
|
+
const mine = await req.payload.count({
|
|
84
|
+
collection: MEMBERS,
|
|
85
|
+
where: { and: [{ link: { equals: idOf(originalDoc.link) } }, { user: { in: people } }] },
|
|
86
|
+
overrideAccess: true,
|
|
87
|
+
req,
|
|
88
|
+
});
|
|
89
|
+
if (mine.totalDocs > 0)
|
|
90
|
+
throw new APIError('You can’t approve a set you belong to. Ask another administrator.', 403, undefined, true);
|
|
91
|
+
return { ...data, approvedBy: me.id, approvedAt: new Date().toISOString() };
|
|
92
|
+
},
|
|
93
|
+
],
|
|
94
|
+
afterChange: [
|
|
95
|
+
async ({ doc, previousDoc, operation, req }) => {
|
|
96
|
+
if (operation === 'update' && previousDoc?.status !== 'approved' && doc.status === 'approved' && !internal(req))
|
|
97
|
+
await opts.onEvent?.({ type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
|
|
98
|
+
},
|
|
99
|
+
],
|
|
100
|
+
afterDelete: [
|
|
101
|
+
async ({ doc, req }) => {
|
|
102
|
+
const link = idOf(doc.link);
|
|
103
|
+
const account = idOf(doc.user);
|
|
104
|
+
await revokeSessions(req.payload, { and: [{ link: { equals: link } }, { or: [{ user: { equals: account } }, { via: { equals: account } }] }] }, 'unlinked', req);
|
|
105
|
+
if (!internal(req))
|
|
106
|
+
await opts.onEvent?.({ type: 'unlinked', payload: req.payload, link, account, by: req.user ? String(req.user.id) : null });
|
|
107
|
+
if (!req.context?.hatsDissolving)
|
|
108
|
+
await dissolveIfAlone(req.payload, link, req);
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
const sessions = {
|
|
114
|
+
slug: SESSIONS,
|
|
115
|
+
admin: { hidden: true },
|
|
116
|
+
access: { read: never, create: never, update: never, delete: never },
|
|
117
|
+
fields: [
|
|
118
|
+
{ name: 'sid', type: 'text', required: true, unique: true },
|
|
119
|
+
{ name: 'user', type: 'text', required: true, index: true },
|
|
120
|
+
{ name: 'via', type: 'text', index: true },
|
|
121
|
+
{ name: 'link', type: 'text', index: true },
|
|
122
|
+
{ name: 'hat', type: 'text' },
|
|
123
|
+
// Per account: when its second factor was last given in this browser, so switching up is asked again later.
|
|
124
|
+
{ name: 'steppedUp', type: 'json' },
|
|
125
|
+
{ name: 'expiresAt', type: 'date', index: true },
|
|
126
|
+
// Set when the session is ended. Kept so a session Payload puts back by accident stays signed out.
|
|
127
|
+
{ name: 'revokedAt', type: 'date', index: true },
|
|
128
|
+
],
|
|
129
|
+
};
|
|
130
|
+
return [links, members, sessions];
|
|
131
|
+
}
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import { addDataAndFileToRequest, APIError, getFieldsToSign, jwtSign } from 'payload';
|
|
2
|
+
import { addSessionToUser, generateCookie } from 'payload/shared';
|
|
3
|
+
import { blockedBy, exactlyTrue } from './access.js';
|
|
4
|
+
import { cleanupSessions, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
|
|
5
|
+
import { memoryKey, needsStepUp, remembered } from './stepup.js';
|
|
6
|
+
import { asPlugin, hashToken, hatsOptions, hatsStateOf, idOf, newToken } from './state.js';
|
|
7
|
+
import { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
8
|
+
const json = (body, status = 200, cookies = []) => {
|
|
9
|
+
const headers = new Headers({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
10
|
+
for (const c of cookies)
|
|
11
|
+
headers.append('Set-Cookie', c);
|
|
12
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
13
|
+
};
|
|
14
|
+
/** 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) => {
|
|
16
|
+
throw new APIError(message, status, reason ? { reason } : undefined, true);
|
|
17
|
+
};
|
|
18
|
+
/** The acting account, its full record (all roles, not the hat), and the session's hat state. */
|
|
19
|
+
async function actor(req) {
|
|
20
|
+
const opts = hatsOptions(req.payload);
|
|
21
|
+
const user = req.user;
|
|
22
|
+
if (!user || user.collection !== opts.users)
|
|
23
|
+
refuse('Sign in first.', 401, 'signIn');
|
|
24
|
+
const state = hatsStateOf(user);
|
|
25
|
+
if (!state)
|
|
26
|
+
refuse('Switching needs a browser sign-in.', 400, 'signIn');
|
|
27
|
+
const full = await loadUser(req, String(user.id));
|
|
28
|
+
if (!full)
|
|
29
|
+
refuse('Sign in first.', 401, 'signIn');
|
|
30
|
+
return { opts, user: user, full: full, state: state, person: state.via ?? String(user.id) };
|
|
31
|
+
}
|
|
32
|
+
const loadUser = async (req, id) => (await req.payload.findByID({ collection: hatsOptions(req.payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
|
|
33
|
+
const labelOf = (u) => String(u.email ?? u.id);
|
|
34
|
+
async function members(req, link) {
|
|
35
|
+
const { docs } = await req.payload.find({ collection: MEMBERS, where: { link: { equals: link } }, limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
|
|
36
|
+
return docs;
|
|
37
|
+
}
|
|
38
|
+
async function membershipOf(req, userId) {
|
|
39
|
+
const { docs } = await req.payload.find({ collection: MEMBERS, where: { user: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
40
|
+
return docs[0] ?? null;
|
|
41
|
+
}
|
|
42
|
+
/** The other approved accounts in the acting account's set, with their hats. */
|
|
43
|
+
async function linkedAccounts(req, userId) {
|
|
44
|
+
const mine = await membershipOf(req, userId);
|
|
45
|
+
if (mine?.status !== 'approved')
|
|
46
|
+
return { link: null, linked: [] };
|
|
47
|
+
const link = idOf(mine.link);
|
|
48
|
+
const linked = [];
|
|
49
|
+
for (const m of await members(req, link)) {
|
|
50
|
+
if (m.status !== 'approved' || idOf(m.user) === userId)
|
|
51
|
+
continue;
|
|
52
|
+
const u = await loadUser(req, idOf(m.user));
|
|
53
|
+
if (u)
|
|
54
|
+
linked.push({ user: u, hats: hatsOptions(req.payload).hatsOf(u) });
|
|
55
|
+
}
|
|
56
|
+
return { link, linked };
|
|
57
|
+
}
|
|
58
|
+
const defaultShow = ({ hats, linked }) => hats.length > 1 || linked.some((l) => l.hats.length > 1);
|
|
59
|
+
async function blockedReason(req, opts) {
|
|
60
|
+
if (!opts.blocked)
|
|
61
|
+
return;
|
|
62
|
+
const why = await blockedBy(() => opts.blocked(req));
|
|
63
|
+
if (why !== null)
|
|
64
|
+
refuse(why, 409, 'blocked');
|
|
65
|
+
}
|
|
66
|
+
/** GET /api/hats: the switch menu for the acting account. */
|
|
67
|
+
const me = {
|
|
68
|
+
path: '/hats',
|
|
69
|
+
method: 'get',
|
|
70
|
+
handler: async (req) => {
|
|
71
|
+
if (!req.user)
|
|
72
|
+
return json({ signedIn: false });
|
|
73
|
+
const { opts, full, state, person } = await actor(req);
|
|
74
|
+
const hats = opts.hatsOf(full);
|
|
75
|
+
const { link, linked } = await linkedAccounts(req, String(full.id));
|
|
76
|
+
const worn = wornHat(hats, state.hat ? { hat: state.hat, via: state.via } : null) ?? hats.at(-1) ?? null;
|
|
77
|
+
const s = await sessionBySid(req.payload, state.sid, req);
|
|
78
|
+
const mine = await membershipOf(req, String(full.id));
|
|
79
|
+
const from = { user: req.user, hat: worn?.id ?? null };
|
|
80
|
+
const setId = mine?.status === 'approved' ? idOf(mine.link) : null;
|
|
81
|
+
const asks = async (target, targetHats, h, sameAccount) => !(sameAccount && h.id === worn?.id) && (await needsStepUp(opts, { req, from, target, hats: targetHats, hat: h })) && !remembered(opts, s?.steppedUp, String(target.id), setId);
|
|
82
|
+
// The set as this account may see it: an account nobody has confirmed yet stays hidden, so a request never
|
|
83
|
+
// reveals whether an email has an account here.
|
|
84
|
+
const set = [];
|
|
85
|
+
if (mine)
|
|
86
|
+
for (const m of await members(req, idOf(mine.link))) {
|
|
87
|
+
const you = idOf(m.user) === String(full.id);
|
|
88
|
+
if (!you && m.status === 'requested')
|
|
89
|
+
continue;
|
|
90
|
+
const u = you ? full : await loadUser(req, idOf(m.user));
|
|
91
|
+
if (u)
|
|
92
|
+
set.push({ id: u.id, label: labelOf(u), status: m.status, you });
|
|
93
|
+
}
|
|
94
|
+
return json({
|
|
95
|
+
signedIn: true,
|
|
96
|
+
account: { id: full.id, label: labelOf(full) },
|
|
97
|
+
signedInAs: person,
|
|
98
|
+
hat: worn?.id ?? null,
|
|
99
|
+
hats: await Promise.all(hats.map(async (h) => ({ ...h, needsCode: await asks(full, hats, h, true) }))),
|
|
100
|
+
linked: await Promise.all(linked.map(async (l) => ({
|
|
101
|
+
id: l.user.id,
|
|
102
|
+
label: labelOf(l.user),
|
|
103
|
+
hats: await Promise.all(l.hats.map(async (h) => ({ ...h, needsCode: await asks(l.user, l.hats, h, false) }))),
|
|
104
|
+
}))),
|
|
105
|
+
link,
|
|
106
|
+
set,
|
|
107
|
+
canLink: Boolean(opts.canApproveLinks),
|
|
108
|
+
showSwitch: (opts.showSwitch ?? defaultShow)({ user: full, hats, linked }),
|
|
109
|
+
maxLinked: opts.maxLinked,
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* POST /api/hats/switch { account?, hat, code? }: wear another hat, on this account or another approved account in
|
|
115
|
+
* the same set. A sensitive hat needs that account's second factor unless it was given here recently.
|
|
116
|
+
*/
|
|
117
|
+
const switchHat = {
|
|
118
|
+
path: '/hats/switch',
|
|
119
|
+
method: 'post',
|
|
120
|
+
handler: async (req) => {
|
|
121
|
+
await addDataAndFileToRequest(req);
|
|
122
|
+
const { opts, full, state, person } = await actor(req);
|
|
123
|
+
await blockedReason(req, opts);
|
|
124
|
+
const body = (req.data ?? {});
|
|
125
|
+
const current = String(full.id);
|
|
126
|
+
const to = body.account == null || body.account === '' ? current : String(body.account);
|
|
127
|
+
let link = null;
|
|
128
|
+
if (to !== current) {
|
|
129
|
+
link = await sharedLink(req.payload, current, to, req);
|
|
130
|
+
if (!link)
|
|
131
|
+
refuse('That account isn’t linked to this one.', 403, 'notLinked');
|
|
132
|
+
}
|
|
133
|
+
const target = to === current ? full : await loadUser(req, to);
|
|
134
|
+
if (!target)
|
|
135
|
+
refuse('That account isn’t linked to this one.', 403, 'notLinked');
|
|
136
|
+
const { linked } = await linkedAccounts(req, current);
|
|
137
|
+
if (!(opts.showSwitch ?? defaultShow)({ user: full, hats: opts.hatsOf(full), linked }))
|
|
138
|
+
refuse('Switching isn’t available for this account.', 403, 'notAvailable');
|
|
139
|
+
const hats = opts.hatsOf(target);
|
|
140
|
+
const hat = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
|
|
141
|
+
if (!hat)
|
|
142
|
+
refuse('Choose one of that account’s hats.', 400, 'chooseHat');
|
|
143
|
+
const s = await sessionBySid(req.payload, state.sid, req);
|
|
144
|
+
const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
|
|
145
|
+
const steppedUp = { ...(s?.steppedUp ?? {}) };
|
|
146
|
+
let gaveCode = false;
|
|
147
|
+
const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
|
|
148
|
+
const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
|
|
149
|
+
if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
|
|
150
|
+
if (!opts.stepUp)
|
|
151
|
+
refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
|
|
152
|
+
// Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
|
|
153
|
+
const stepUp = opts.stepUp;
|
|
154
|
+
const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId };
|
|
155
|
+
if (!(await exactlyTrue(() => stepUp.available(target, ctx))))
|
|
156
|
+
refuse('Set up two-step sign-in on that account first.', 403, 'setUpTwoStep');
|
|
157
|
+
const code = typeof body.code === 'string' ? body.code.trim() : '';
|
|
158
|
+
if (!code)
|
|
159
|
+
return json({ ok: false, needsCode: true, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' }, 401);
|
|
160
|
+
if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
|
|
161
|
+
refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
|
|
162
|
+
steppedUp[memoryKey(opts, to, setId)] = new Date().toISOString();
|
|
163
|
+
gaveCode = true;
|
|
164
|
+
}
|
|
165
|
+
const users = req.payload.collections[opts.users].config;
|
|
166
|
+
if (to === current) {
|
|
167
|
+
await asPlugin(req, async () => {
|
|
168
|
+
if (s)
|
|
169
|
+
await req.payload.update({ collection: SESSIONS, id: s.id, data: { hat: hat.id, steppedUp }, overrideAccess: true, req });
|
|
170
|
+
else
|
|
171
|
+
await req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req });
|
|
172
|
+
});
|
|
173
|
+
await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
|
|
174
|
+
return json({ ok: true, account: to, hat: hat.id, reload: true });
|
|
175
|
+
}
|
|
176
|
+
// Another account: a fresh Payload session for it, then this one ends.
|
|
177
|
+
const own = person === to;
|
|
178
|
+
const { sid } = await addSessionToUser({ collectionConfig: users, payload: req.payload, req, user: target });
|
|
179
|
+
if (!sid)
|
|
180
|
+
refuse('Switching accounts needs Payload sessions (auth.useSessions).', 500);
|
|
181
|
+
await asPlugin(req, () => req.payload.create({
|
|
182
|
+
collection: SESSIONS,
|
|
183
|
+
data: { sid, user: to, via: own ? null : person, link: own ? null : link, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) },
|
|
184
|
+
overrideAccess: true,
|
|
185
|
+
req,
|
|
186
|
+
}));
|
|
187
|
+
await revokeSid(req.payload, current, state.sid, req);
|
|
188
|
+
if (s)
|
|
189
|
+
await tombstone(req.payload, s.id, req);
|
|
190
|
+
else
|
|
191
|
+
await asPlugin(req, () => req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, revokedAt: new Date().toISOString(), expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req }));
|
|
192
|
+
await cleanupSessions(req.payload, req).catch((err) => req.payload.logger.warn({ err }, 'Hats: session clean-up skipped'));
|
|
193
|
+
const { token } = await jwtSign({
|
|
194
|
+
fieldsToSign: getFieldsToSign({ collectionConfig: users, email: String(target.email ?? ''), sid, user: target }),
|
|
195
|
+
secret: req.payload.secret,
|
|
196
|
+
tokenExpiration: users.auth.tokenExpiration,
|
|
197
|
+
});
|
|
198
|
+
const cookie = generateCookie({
|
|
199
|
+
name: `${req.payload.config.cookiePrefix}-token`,
|
|
200
|
+
value: token,
|
|
201
|
+
path: '/',
|
|
202
|
+
httpOnly: true,
|
|
203
|
+
secure: users.auth.cookies.secure,
|
|
204
|
+
sameSite: typeof users.auth.cookies.sameSite === 'string' ? users.auth.cookies.sameSite : 'Lax',
|
|
205
|
+
domain: users.auth.cookies.domain ?? undefined,
|
|
206
|
+
expires: new Date(Date.now() + users.auth.tokenExpiration * 1000),
|
|
207
|
+
returnCookieAsObject: false,
|
|
208
|
+
});
|
|
209
|
+
await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
|
|
210
|
+
return json({ ok: true, account: to, hat: hat.id, reload: true }, 200, [cookie]);
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
const expiry = (seconds) => new Date(Date.now() + seconds * 1000).toISOString();
|
|
214
|
+
const SENT = 'If that account can be linked, we’ve emailed it a link to confirm. Confirm from your own email too; then an administrator reviews the link.';
|
|
215
|
+
/** POST /api/hats/link { email }: ask to link the acting account with another. Says the same thing whatever happens to the other account. */
|
|
216
|
+
const requestLink = {
|
|
217
|
+
path: '/hats/link',
|
|
218
|
+
method: 'post',
|
|
219
|
+
handler: async (req) => {
|
|
220
|
+
await addDataAndFileToRequest(req);
|
|
221
|
+
const { opts, full } = await actor(req);
|
|
222
|
+
await blockedReason(req, opts);
|
|
223
|
+
if (!opts.canApproveLinks)
|
|
224
|
+
refuse('Linking accounts isn’t turned on here.', 403, 'linkingOff');
|
|
225
|
+
const email = String(req.data?.email ?? '').trim().toLowerCase();
|
|
226
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
227
|
+
refuse('Enter the other account’s email address.', 400, 'enterEmail');
|
|
228
|
+
// Refused unless the site's limit answers exactly true (a throw, false or any other answer is a no): nothing is recorded or sent.
|
|
229
|
+
if (opts.limit && !(await exactlyTrue(() => opts.limit({ req, user: full, email }))))
|
|
230
|
+
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
231
|
+
const me = String(full.id);
|
|
232
|
+
const now = new Date();
|
|
233
|
+
await asPlugin(req, async () => {
|
|
234
|
+
// Requests nobody confirmed in time don't hold anyone up.
|
|
235
|
+
await req.payload.delete({
|
|
236
|
+
collection: MEMBERS,
|
|
237
|
+
where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] },
|
|
238
|
+
overrideAccess: true,
|
|
239
|
+
showHiddenFields: true,
|
|
240
|
+
req,
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
const mine = await membershipOf(req, me);
|
|
244
|
+
const already = mine ? (await members(req, idOf(mine.link))).length : 0;
|
|
245
|
+
if (already + (mine ? 1 : 2) > opts.maxLinked)
|
|
246
|
+
refuse(`A set can hold at most ${opts.maxLinked} accounts.`, 400, 'setFull');
|
|
247
|
+
const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
248
|
+
const target = docs[0];
|
|
249
|
+
if (!target || String(target.id) === me || (await membershipOf(req, String(target.id))))
|
|
250
|
+
return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
|
|
251
|
+
const hours = opts.confirmHours;
|
|
252
|
+
const invite = async (user, link) => {
|
|
253
|
+
const token = newToken();
|
|
254
|
+
await req.payload.create({
|
|
255
|
+
collection: MEMBERS,
|
|
256
|
+
data: { link, user: user.id, status: 'requested', tokenHash: hashToken(token), tokenExpires: new Date(now.getTime() + hours * 3_600_000).toISOString(), addedBy: me },
|
|
257
|
+
overrideAccess: true,
|
|
258
|
+
req,
|
|
259
|
+
});
|
|
260
|
+
const url = opts.confirmURL ? opts.confirmURL({ req, token }) : `${new URL(req.url ?? 'http://localhost').origin}${req.payload.config.routes.api}/hats/confirm?token=${token}`;
|
|
261
|
+
await opts.sendEmail({
|
|
262
|
+
payload: req.payload,
|
|
263
|
+
to: String(user.email),
|
|
264
|
+
subject: 'Confirm linking your accounts',
|
|
265
|
+
text: `Someone asked to link ${labelOf(full)} and ${labelOf(target)}, so one person can switch between them.\n\nIf that was you, confirm here within ${hours} hours:\n${url}\n\nIf it wasn’t you, ignore this email: nothing is linked without it.`,
|
|
266
|
+
});
|
|
267
|
+
};
|
|
268
|
+
let link = mine ? idOf(mine.link) : null;
|
|
269
|
+
try {
|
|
270
|
+
await asPlugin(req, async () => {
|
|
271
|
+
if (!link)
|
|
272
|
+
link = String((await req.payload.create({ collection: LINKS, data: { requestedBy: me, label: `Started by ${labelOf(full)}` }, overrideAccess: true, req })).id);
|
|
273
|
+
if (!mine)
|
|
274
|
+
await invite(full, link);
|
|
275
|
+
await invite(target, link);
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
// Someone else linked that account a moment ago (the one-set-per-account index): say the same as always.
|
|
280
|
+
req.payload.logger.warn({ err: error }, 'Hats: link request not recorded');
|
|
281
|
+
return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
|
|
282
|
+
}
|
|
283
|
+
await opts.onEvent?.({ type: 'link-requested', req, link: link, by: me, account: String(target.id) });
|
|
284
|
+
return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
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' } });
|
|
288
|
+
const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
289
|
+
/** GET /api/hats/confirm?token=…: a button, so a mail scanner opening the link doesn't confirm anything. */
|
|
290
|
+
const confirmPage = {
|
|
291
|
+
path: '/hats/confirm',
|
|
292
|
+
method: 'get',
|
|
293
|
+
handler: async (req) => {
|
|
294
|
+
const token = new URL(req.url ?? 'http://localhost').searchParams.get('token') ?? '';
|
|
295
|
+
return page('Link your accounts', `<p>Confirm that this account belongs to the person who asked to link it. An administrator reviews the link before it works.</p><form method="post"><input type="hidden" name="token" value="${esc(token)}"><button type="submit">Confirm</button></form>`);
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
/** POST /api/hats/confirm (form or JSON { token }). */
|
|
299
|
+
const confirm = {
|
|
300
|
+
path: '/hats/confirm',
|
|
301
|
+
method: 'post',
|
|
302
|
+
handler: async (req) => {
|
|
303
|
+
let token = '';
|
|
304
|
+
const type = req.headers.get('content-type') ?? '';
|
|
305
|
+
if (type.includes('application/x-www-form-urlencoded') && req.text)
|
|
306
|
+
token = new URLSearchParams(await req.text()).get('token') ?? '';
|
|
307
|
+
else {
|
|
308
|
+
await addDataAndFileToRequest(req);
|
|
309
|
+
token = String(req.data?.token ?? '');
|
|
310
|
+
}
|
|
311
|
+
const bad = () => page('That link didn’t work', '<p>It may have expired or been used already. Ask again from your account page.</p>', 400);
|
|
312
|
+
if (!token)
|
|
313
|
+
return bad();
|
|
314
|
+
const { docs } = await req.payload.find({ collection: MEMBERS, where: { tokenHash: { equals: hashToken(token) } }, limit: 1, depth: 0, overrideAccess: true, showHiddenFields: true, pagination: false, req });
|
|
315
|
+
const m = docs[0];
|
|
316
|
+
if (!m || m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
|
|
317
|
+
return bad();
|
|
318
|
+
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 }));
|
|
319
|
+
await hatsOptions(req.payload).onEvent?.({ type: 'link-confirmed', payload: req.payload, link: idOf(m.link), account: idOf(m.user) });
|
|
320
|
+
return page('Confirmed', '<p>Thanks. Once every account in the link is confirmed, an administrator reviews it. You can close this page.</p>');
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
/** POST /api/hats/unlink { account? }: take an account (default: the acting one) out of the set. Self-serve, at once. */
|
|
324
|
+
const unlink = {
|
|
325
|
+
path: '/hats/unlink',
|
|
326
|
+
method: 'post',
|
|
327
|
+
handler: async (req) => {
|
|
328
|
+
await addDataAndFileToRequest(req);
|
|
329
|
+
const { opts, full, person } = await actor(req);
|
|
330
|
+
await blockedReason(req, opts);
|
|
331
|
+
const me = String(full.id);
|
|
332
|
+
const account = String(req.data?.account ?? me);
|
|
333
|
+
const mine = await membershipOf(req, me);
|
|
334
|
+
const theirs = account === me ? mine : await membershipOf(req, account);
|
|
335
|
+
if (!mine || !theirs || idOf(mine.link) !== idOf(theirs.link))
|
|
336
|
+
refuse('That account isn’t in your linked set.', 404, 'notInSet');
|
|
337
|
+
const link = idOf(theirs.link);
|
|
338
|
+
await asPlugin(req, () => req.payload.delete({ collection: MEMBERS, id: theirs.id, overrideAccess: true, req }));
|
|
339
|
+
await opts.onEvent?.({ type: 'unlinked', payload: req.payload, link, account, by: me });
|
|
340
|
+
// If this session was switched in through the account just removed, it ended with the unlink.
|
|
341
|
+
return json({ ok: true, signedOut: account === me ? person !== me : person === account });
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
export const hatEndpoints = [me, switchHat, requestLink, confirmPage, confirm, unlink];
|
|
345
|
+
export { revokeSessions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Plugin } from 'payload';
|
|
2
|
+
import { type HatsOptions } from './types.js';
|
|
3
|
+
export { hatsStateOf } from './state.js';
|
|
4
|
+
export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
|
|
5
|
+
export { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
6
|
+
export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, StepUpContext } from './types.js';
|
|
7
|
+
/**
|
|
8
|
+
* Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
|
|
9
|
+
* holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
|
|
10
|
+
* factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
|
|
11
|
+
* the membership or the account's roles change.
|
|
12
|
+
*/
|
|
13
|
+
export declare const hats: (options: HatsOptions) => Plugin;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { hatCollections } from './collections.js';
|
|
2
|
+
import { hatEndpoints } from './endpoints.js';
|
|
3
|
+
import { revokeSessions, wrapStrategies } from './sessions.js';
|
|
4
|
+
import { asPlugin } from './state.js';
|
|
5
|
+
import { MEMBERS, SESSIONS } from './types.js';
|
|
6
|
+
export { hatsStateOf } from './state.js';
|
|
7
|
+
export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
|
|
8
|
+
export { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
9
|
+
/**
|
|
10
|
+
* Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
|
|
11
|
+
* holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
|
|
12
|
+
* factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
|
|
13
|
+
* the membership or the account's roles change.
|
|
14
|
+
*/
|
|
15
|
+
export const hats = (options) => (config) => {
|
|
16
|
+
const opts = {
|
|
17
|
+
users: 'users',
|
|
18
|
+
maxLinked: 4,
|
|
19
|
+
confirmHours: 24,
|
|
20
|
+
showSwitch: undefined,
|
|
21
|
+
adminSwitch: true,
|
|
22
|
+
sendEmail: ({ payload, to, subject, text }) => payload.sendEmail({ to, subject, text }),
|
|
23
|
+
...options,
|
|
24
|
+
};
|
|
25
|
+
if (opts.maxLinked < 2)
|
|
26
|
+
throw new Error('hats: maxLinked must be at least 2.');
|
|
27
|
+
const users = (config.collections ?? []).find((c) => c.slug === opts.users);
|
|
28
|
+
if (!users?.auth)
|
|
29
|
+
throw new Error(`hats: no auth collection "${opts.users}".`);
|
|
30
|
+
if (typeof users.auth === 'object' && users.auth.useSessions === false)
|
|
31
|
+
throw new Error('hats: needs Payload sessions; remove auth.useSessions: false.');
|
|
32
|
+
for (const slug of ['hat-links', MEMBERS, SESSIONS])
|
|
33
|
+
if ((config.collections ?? []).some((c) => c.slug === slug))
|
|
34
|
+
throw new Error(`hats: a collection "${slug}" already exists.`);
|
|
35
|
+
const ids = (u) => new Set(opts.hatsOf(u).map((h) => h.id));
|
|
36
|
+
// Losing a hat ends every session switched into the account: it comes back in through the switch, re-checked.
|
|
37
|
+
const afterChange = async ({ doc, previousDoc, operation, req }) => {
|
|
38
|
+
if (operation !== 'update' || !previousDoc)
|
|
39
|
+
return doc;
|
|
40
|
+
const now = ids(doc);
|
|
41
|
+
if ([...ids(previousDoc)].some((h) => !now.has(h)))
|
|
42
|
+
await revokeSessions(req.payload, { and: [{ user: { equals: String(doc.id) } }, { via: { exists: true } }, { via: { not_equals: null } }] }, 'lost a role', req);
|
|
43
|
+
return doc;
|
|
44
|
+
};
|
|
45
|
+
const afterDelete = async ({ id, req }) => {
|
|
46
|
+
await revokeSessions(req.payload, { or: [{ user: { equals: String(id) } }, { via: { equals: String(id) } }] }, 'account deleted', req);
|
|
47
|
+
await asPlugin(req, () => req.payload.delete({ collection: MEMBERS, where: { user: { equals: String(id) } }, overrideAccess: true, req }));
|
|
48
|
+
};
|
|
49
|
+
const afterLogout = async ({ req }) => {
|
|
50
|
+
const sid = req.user?._sid;
|
|
51
|
+
if (sid)
|
|
52
|
+
await req.payload.update({ collection: SESSIONS, where: { sid: { equals: sid } }, data: { revokedAt: new Date().toISOString() }, overrideAccess: true, req });
|
|
53
|
+
};
|
|
54
|
+
const onInit = config.onInit;
|
|
55
|
+
return {
|
|
56
|
+
...config,
|
|
57
|
+
collections: [
|
|
58
|
+
...(config.collections ?? []).map((c) => c.slug === opts.users
|
|
59
|
+
? {
|
|
60
|
+
...c,
|
|
61
|
+
hooks: {
|
|
62
|
+
...c.hooks,
|
|
63
|
+
afterChange: [...(c.hooks?.afterChange ?? []), afterChange],
|
|
64
|
+
afterDelete: [...(c.hooks?.afterDelete ?? []), afterDelete],
|
|
65
|
+
afterLogout: [...(c.hooks?.afterLogout ?? []), afterLogout],
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
: c),
|
|
69
|
+
...hatCollections(opts),
|
|
70
|
+
],
|
|
71
|
+
endpoints: [...(config.endpoints ?? []), ...hatEndpoints],
|
|
72
|
+
admin: opts.adminSwitch === false
|
|
73
|
+
? config.admin
|
|
74
|
+
: { ...config.admin, components: { ...config.admin?.components, actions: [...(config.admin?.components?.actions ?? []), '@extantape/payload-plugin-hats/client#HatSwitcher'] } },
|
|
75
|
+
custom: { ...config.custom, hats: opts },
|
|
76
|
+
onInit: async (payload) => {
|
|
77
|
+
await onInit?.(payload);
|
|
78
|
+
wrapStrategies(payload, opts);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest, Where } from 'payload';
|
|
2
|
+
import { type Hat, type HatsUser, type ResolvedHatsOptions } from './types.js';
|
|
3
|
+
type SessionDoc = {
|
|
4
|
+
id: string;
|
|
5
|
+
sid: string;
|
|
6
|
+
user: string;
|
|
7
|
+
via?: string | null;
|
|
8
|
+
link?: string | null;
|
|
9
|
+
hat?: string | null;
|
|
10
|
+
steppedUp?: Record<string, string> | null;
|
|
11
|
+
revokedAt?: string | null;
|
|
12
|
+
expiresAt?: string | null;
|
|
13
|
+
};
|
|
14
|
+
export declare function sessionBySid(payload: Payload, sid: string, req?: PayloadRequest): Promise<SessionDoc | null>;
|
|
15
|
+
/** Removes one Payload session from an account, so its token stops working everywhere at once. */
|
|
16
|
+
export declare function revokeSid(payload: Payload, userId: string, sid: string, req?: PayloadRequest): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Marks a session's record revoked instead of deleting it. Payload writes a user's whole `sessions` list at once, so a
|
|
19
|
+
* sign-in at the same moment can put a revoked session back; the tombstone makes sure that session stays signed out,
|
|
20
|
+
* rather than looking like a plain sign-in with every role. Tombstones go once they can't matter (`cleanupSessions`).
|
|
21
|
+
*/
|
|
22
|
+
export declare function tombstone(payload: Payload, id: string, req?: PayloadRequest): Promise<void>;
|
|
23
|
+
/** Ends every switched session matching `where` (and its Payload session), e.g. after an unlink. */
|
|
24
|
+
export declare function revokeSessions(payload: Payload, where: Where, reason: string, req?: PayloadRequest): Promise<number>;
|
|
25
|
+
/** A set with one account left isn't a link any more: remove it. */
|
|
26
|
+
export declare function dissolveIfAlone(payload: Payload, link: string, req: PayloadRequest): Promise<void>;
|
|
27
|
+
/** The approved set two accounts are both in, or null. Read fresh every time. */
|
|
28
|
+
export declare function sharedLink(payload: Payload, a: string, b: string, req?: PayloadRequest): Promise<string | null>;
|
|
29
|
+
/** The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest. */
|
|
30
|
+
export declare function wornHat(hats: Hat[], s: Pick<SessionDoc, 'hat' | 'via'> | null): Hat | null;
|
|
31
|
+
/**
|
|
32
|
+
* The user as the rest of the site sees them: narrowed to the hat this session wears. A switched session whose set
|
|
33
|
+
* is gone is revoked and signed out. Anything unexpected throws, which signs the request out: never full roles.
|
|
34
|
+
*/
|
|
35
|
+
export declare function applyHat(payload: Payload, opts: ResolvedHatsOptions, user: HatsUser): Promise<HatsUser | null>;
|
|
36
|
+
/** Every auth strategy, wrapped so a signed-in user of our collection is narrowed before `req.user` exists. */
|
|
37
|
+
export declare function wrapStrategies(payload: Payload, opts: ResolvedHatsOptions): void;
|
|
38
|
+
/**
|
|
39
|
+
* Deletes session records that can't matter any more: expired over a day ago, and with no unexpired Payload session
|
|
40
|
+
* of that id left on the account. A record whose Payload session was kept alive (a refresh moves its expiry) stays,
|
|
41
|
+
* because deleting it would turn a narrowed or switched session into a plain one. At most `max` per call.
|
|
42
|
+
*/
|
|
43
|
+
export declare function cleanupSessions(payload: Payload, req?: PayloadRequest, max?: number): Promise<number>;
|
|
44
|
+
export {};
|