@extantape/payload-plugin-hats 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/endpoints.js CHANGED
@@ -3,8 +3,8 @@ import { addSessionToUser, generateCookie } from 'payload/shared';
3
3
  import { blockedBy, exactlyTrue } from './access.js';
4
4
  import { cleanupSessions, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
5
5
  import { memoryKey, needsStepUp, remembered } from './stepup.js';
6
- import { asPlugin, hashToken, hatsOptions, hatsStateOf, idOf, newToken } from './state.js';
7
- import { LINKS, MEMBERS, SESSIONS } from './types.js';
6
+ import { asPlugin, DISSOLVING, hashToken, hatsOptions, hatsStateOf, idOf, newToken, relId, removeWhere, tell, trackWork, unmarked, withMark } from './state.js';
7
+ import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
8
8
  const json = (body, status = 200, cookies = []) => {
9
9
  const headers = new Headers({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
10
10
  for (const c of cookies)
@@ -37,7 +37,9 @@ async function members(req, link) {
37
37
  }
38
38
  async function membershipOf(req, userId) {
39
39
  const { docs } = await req.payload.find({ collection: MEMBERS, where: { user: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
40
- return docs[0] ?? null;
40
+ const row = docs[0] ?? null;
41
+ // Only a row for exactly this account: on MongoDB the text "null" can match a row whose account was cleared.
42
+ return row && row.user != null && idOf(row.user) === userId ? row : null;
41
43
  }
42
44
  /** The other approved accounts in the acting account's set, with their hats. */
43
45
  async function linkedAccounts(req, userId) {
@@ -110,6 +112,173 @@ const me = {
110
112
  });
111
113
  },
112
114
  };
115
+ /**
116
+ * The one switch, shared by POST /api/hats/switch and `switchSession`, so the two can't drift. It acts only for
117
+ * `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
118
+ */
119
+ export async function runSwitch(req, input) {
120
+ try {
121
+ return await switchCore(req, input ?? {});
122
+ }
123
+ catch (error) {
124
+ if (error instanceof APIError) {
125
+ const reason = error.data?.reason;
126
+ return { ok: false, status: error.status, reason: typeof reason === 'string' ? reason : 'failed', message: error.message };
127
+ }
128
+ req.payload?.logger?.warn({ err: error }, 'Hats: switch refused after an unexpected error');
129
+ return { ok: false, status: 500, reason: 'failed', message: 'Switching didn’t work. Try again.' };
130
+ }
131
+ }
132
+ /** The origins this site answers as: the one the request arrived on, and the configured server URL. */
133
+ function ownOrigins(req) {
134
+ const out = [];
135
+ for (const u of [req.url, req.payload?.config?.serverURL]) {
136
+ try {
137
+ if (u)
138
+ out.push(new URL(u).origin);
139
+ }
140
+ catch {
141
+ /* an unreadable address adds no origin, so a mismatch is refused */
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+ /** Reads a header from a Headers instance or a plain object (any key case). Null for anything else, which is refused as cross-site. */
147
+ function headerReader(h) {
148
+ if (h instanceof Headers)
149
+ return (name) => h.get(name);
150
+ const proto = h && typeof h === 'object' ? Object.getPrototypeOf(h) : undefined;
151
+ if (proto !== Object.prototype && proto !== null)
152
+ return null;
153
+ const entries = Object.entries(h);
154
+ // Header values are strings (or lists of them, as Node gives them); a function or anything else means this isn't headers.
155
+ const plain = (v) => v == null || typeof v === 'string' || (Array.isArray(v) && v.every((x) => typeof x === 'string'));
156
+ if (!entries.every(([, v]) => plain(v)))
157
+ return null;
158
+ return (name) => {
159
+ const hit = entries.find(([k]) => k.toLowerCase() === name);
160
+ if (!hit)
161
+ return null;
162
+ const v = hit[1];
163
+ return Array.isArray(v) ? v.join(', ') : v == null ? null : String(v);
164
+ };
165
+ }
166
+ /** A switch only comes from the site's own POST: any other method, a foreign Origin or a Sec-Fetch-Site other than same-origin is refused. */
167
+ function refuseCrossSite(req) {
168
+ if (String(req.method ?? '').toUpperCase() !== 'POST')
169
+ refuse('Switching needs a POST from this site.', 405, 'notPost');
170
+ const header = headerReader(req.headers);
171
+ if (!header)
172
+ return refuse('Switching must come from this site.', 403, 'crossSite'); // no headers to check, so no way to tell: refused
173
+ const origin = header('origin');
174
+ if (origin != null && !ownOrigins(req).includes(origin))
175
+ refuse('Switching must come from this site.', 403, 'crossSite');
176
+ const fetchSite = header('sec-fetch-site');
177
+ if (fetchSite != null && fetchSite !== 'same-origin')
178
+ refuse('Switching must come from this site.', 403, 'crossSite');
179
+ }
180
+ async function switchCore(req, body) {
181
+ refuseCrossSite(req);
182
+ const { opts, full, state, person } = await actor(req);
183
+ await blockedReason(req, opts);
184
+ const current = String(full.id);
185
+ const to = body.account == null || body.account === '' ? current : String(body.account);
186
+ // Only an id exactly as the account has it. Anything else answers as an account that isn't linked, before any query.
187
+ if (to !== current && !exactId(req, opts, body.account))
188
+ refuse('That account isn’t linked to this one.', 403, 'notLinked');
189
+ let link = null;
190
+ if (to !== current) {
191
+ link = await sharedLink(req.payload, current, to, req);
192
+ if (!link)
193
+ refuse('That account isn’t linked to this one.', 403, 'notLinked');
194
+ }
195
+ const target = to === current ? full : await loadUser(req, to);
196
+ if (!target)
197
+ refuse('That account isn’t linked to this one.', 403, 'notLinked');
198
+ // Direct login refuses a locked account, so a switch into one is refused too.
199
+ const lockUntil = to === current ? null : target.lockUntil;
200
+ if (lockUntil != null && new Date(lockUntil).getTime() > Date.now())
201
+ refuse('That account is locked. Try again later.', 403, 'locked');
202
+ // Direct login refuses an unverified account when the collection verifies emails, so a switch does too.
203
+ const usersAuth = req.payload.collections[opts.users].config.auth;
204
+ if (to !== current && usersAuth.verify && target._verified === false)
205
+ refuse('That account’s email isn’t confirmed yet.', 403, 'unverified');
206
+ const { linked } = await linkedAccounts(req, current);
207
+ if (!(opts.showSwitch ?? defaultShow)({ user: full, hats: opts.hatsOf(full), linked }))
208
+ refuse('Switching isn’t available for this account.', 403, 'notAvailable');
209
+ const hats = opts.hatsOf(target);
210
+ const hat = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
211
+ if (!hat)
212
+ refuse('Choose one of that account’s hats.', 400, 'chooseHat');
213
+ const s = await sessionBySid(req.payload, state.sid, req);
214
+ const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
215
+ const steppedUp = { ...(s?.steppedUp ?? {}) };
216
+ let gaveCode = false;
217
+ const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
218
+ const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
219
+ if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
220
+ if (!opts.stepUp)
221
+ refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
222
+ // Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
223
+ const stepUp = opts.stepUp;
224
+ const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId };
225
+ if (!(await exactlyTrue(() => stepUp.available(target, ctx))))
226
+ refuse('Set up two-step sign-in on that account first.', 403, 'setUpTwoStep');
227
+ const code = typeof body.code === 'string' ? body.code.trim() : '';
228
+ if (!code)
229
+ return { ok: false, status: 401, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' };
230
+ if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
231
+ refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
232
+ steppedUp[memoryKey(opts, to, setId)] = new Date().toISOString();
233
+ gaveCode = true;
234
+ }
235
+ const users = req.payload.collections[opts.users].config;
236
+ if (to === current) {
237
+ await asPlugin(req, async () => {
238
+ if (s)
239
+ await req.payload.update({ collection: SESSIONS, id: s.id, data: { hat: hat.id, steppedUp }, overrideAccess: true, req });
240
+ else
241
+ await req.payload.create({ collection: SESSIONS, data: { sid: state.sid, user: current, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) }, overrideAccess: true, req });
242
+ });
243
+ await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
244
+ return { ok: true, account: to, hat: hat.id, cookie: null };
245
+ }
246
+ // Another account: a fresh Payload session for it, then this one ends.
247
+ const own = person === to;
248
+ const { sid } = await addSessionToUser({ collectionConfig: users, payload: req.payload, req, user: target });
249
+ if (!sid)
250
+ refuse('Switching accounts needs Payload sessions (auth.useSessions).', 500, 'noSessions');
251
+ await asPlugin(req, () => req.payload.create({
252
+ collection: SESSIONS,
253
+ data: { sid, user: to, via: own ? null : person, link: own ? null : link, hat: hat.id, steppedUp, expiresAt: expiry(users.auth.tokenExpiration) },
254
+ overrideAccess: true,
255
+ req,
256
+ }));
257
+ await revokeSid(req.payload, current, state.sid, req);
258
+ if (s)
259
+ await tombstone(req.payload, s.id, req);
260
+ else
261
+ 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 }));
262
+ await cleanupSessions(req.payload, req).catch((err) => req.payload.logger.warn({ err }, 'Hats: session clean-up skipped'));
263
+ const { token } = await jwtSign({
264
+ fieldsToSign: getFieldsToSign({ collectionConfig: users, email: String(target.email ?? ''), sid, user: target }),
265
+ secret: req.payload.secret,
266
+ tokenExpiration: users.auth.tokenExpiration,
267
+ });
268
+ const cookie = generateCookie({
269
+ name: `${req.payload.config.cookiePrefix}-token`,
270
+ value: token,
271
+ path: '/',
272
+ httpOnly: true,
273
+ secure: users.auth.cookies.secure,
274
+ sameSite: typeof users.auth.cookies.sameSite === 'string' ? users.auth.cookies.sameSite : 'Lax',
275
+ domain: users.auth.cookies.domain ?? undefined,
276
+ expires: new Date(Date.now() + users.auth.tokenExpiration * 1000),
277
+ returnCookieAsObject: false,
278
+ });
279
+ await opts.onEvent?.({ type: 'switched', req, from: current, to, hat: hat.id, via: person, steppedUp: gaveCode });
280
+ return { ok: true, account: to, hat: hat.id, cookie };
281
+ }
113
282
  /**
114
283
  * POST /api/hats/switch { account?, hat, code? }: wear another hat, on this account or another approved account in
115
284
  * the same set. A sensitive hat needs that account's second factor unless it was given here recently.
@@ -119,100 +288,27 @@ const switchHat = {
119
288
  method: 'post',
120
289
  handler: async (req) => {
121
290
  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]);
291
+ const result = await runSwitch(req, (req.data ?? {}));
292
+ if (result.ok)
293
+ return json({ ok: true, account: result.account, hat: result.hat, reload: true }, 200, result.cookie ? [result.cookie] : []);
294
+ if (result.reason === 'needsCode')
295
+ return json({ ok: false, needsCode: true, reason: 'needsCode', message: result.message }, 401);
296
+ return refuse(result.message, result.status, result.reason);
211
297
  },
212
298
  };
213
299
  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. */
300
+ const SENT = 'If that address belongs to an account that can be linked, we’ve emailed it a link to confirm. Once it’s confirmed, we’ll email you to confirm from your side, and then an administrator reviews the link.';
301
+ const confirmLink = async (req, opts, token) => opts.confirmURL ? String(await unmarked(req, () => opts.confirmURL({ req, token }))) : `${new URL(req.url ?? 'http://localhost').origin}${req.payload.config.routes.api}/hats/confirm?token=${token}`;
302
+ /** Open link requests one account may have at once. Counted the same whatever the addresses were. */
303
+ const pendingCap = (opts) => opts.maxLinked * 2;
304
+ /**
305
+ * POST /api/hats/link { email }: ask to link the acting account with another. The person asking learns nothing
306
+ * about the address: the answer, the time it takes, their own email, the records they can read and the records
307
+ * written for them are the same whether or not it has an account, whatever state that account is in. Only the
308
+ * other account hears about it, and nothing changes on the asker's side until that account confirms.
309
+ */
310
+ /** What a request's unique `holds` is: the account invited, or a value of its own that holds nothing. */
311
+ const holdFor = (account) => (account ? `account:${String(account.id)}` : `none:${newToken()}`);
216
312
  const requestLink = {
217
313
  path: '/hats/link',
218
314
  method: 'post',
@@ -230,57 +326,94 @@ const requestLink = {
230
326
  refuse('Too many link requests. Try again later.', 429, 'tooMany');
231
327
  const me = String(full.id);
232
328
  const now = new Date();
329
+ // Everything up to here depends only on the asker and what they typed. From here on the answer waits for the
330
+ // same fixed time whatever happens, so how long the work takes says nothing about the address.
331
+ const answer = new Promise((resolve) => setTimeout(resolve, opts.linkAnswerMs));
233
332
  await asPlugin(req, async () => {
234
333
  // 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
- });
334
+ // Best effort: what isn't removed now goes on a later request, and the request goes on either way.
335
+ for (const swept of [
336
+ await req.payload.delete({ collection: MEMBERS, where: { and: [{ status: { equals: 'requested' } }, { tokenExpires: { less_than: now.toISOString() } }] }, overrideAccess: true, showHiddenFields: true, req }),
337
+ await req.payload.delete({ collection: REQUESTS, where: { expiresAt: { less_than: now.toISOString() } }, overrideAccess: true, req }),
338
+ ])
339
+ if (swept.errors?.length)
340
+ req.payload.logger.warn({ msg: 'Hats: some expired link requests were not removed; a later request retries' });
242
341
  });
243
342
  const mine = await membershipOf(req, me);
244
343
  const already = mine ? (await members(req, idOf(mine.link))).length : 0;
245
- if (already + (mine ? 1 : 2) > opts.maxLinked)
344
+ if (already + (mine ? 1 : 2) > opts.maxLinked) {
345
+ await answer;
246
346
  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) => {
347
+ }
348
+ const open = await req.payload.count({ collection: REQUESTS, where: { requestedBy: { equals: me } }, overrideAccess: true, req });
349
+ if (open.totalDocs >= pendingCap(opts)) {
350
+ await answer;
351
+ refuse('Too many link requests. Try again later.', 429, 'tooMany');
352
+ }
353
+ const work = async () => {
354
+ const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
355
+ const found = docs[0];
356
+ let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
357
+ // One record for every request, with the same fields. Only a real invitation's token can ever be used.
253
358
  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 },
359
+ const hours = opts.confirmHours;
360
+ const hold = holdFor(null);
361
+ const request = (await asPlugin(req, () => req.payload.create({
362
+ collection: REQUESTS,
363
+ 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 },
257
364
  overrideAccess: true,
258
365
  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
- });
366
+ })));
367
+ // One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
368
+ // rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
369
+ // the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
370
+ // means no invitation, so the asker sees the same thing either way.
371
+ const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
372
+ const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
373
+ if (!claimed)
374
+ target = null;
375
+ // The asker's own note is the same every time and leaves the address out, so it can't tell them anything.
376
+ try {
377
+ await opts.sendEmail({
378
+ payload: req.payload,
379
+ to: String(full.email),
380
+ subject: 'You asked to link an account',
381
+ 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.`,
382
+ });
383
+ }
384
+ catch (err) {
385
+ req.payload.logger.warn({ err }, 'Hats: link request note not sent');
386
+ }
387
+ if (!target)
388
+ return;
389
+ try {
390
+ await opts.sendEmail({
391
+ payload: req.payload,
392
+ to: String(target.email),
393
+ subject: 'Confirm linking your accounts',
394
+ 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.`,
395
+ });
396
+ }
397
+ catch (err) {
398
+ // The invitation never arrived, so its token must never work.
399
+ req.payload.logger.warn({ err }, 'Hats: link invitation not sent');
400
+ await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: { account: null, holds: holdFor(null), tokenHash: null }, overrideAccess: true, req }));
401
+ return;
402
+ }
403
+ // With no set yet, the event waits for confirmation, when the set exists, so `link` is always a real set.
404
+ if (mine)
405
+ await tell(req.payload, req, { type: 'link-requested', req, link: idOf(mine.link), by: me, account: String(target.id) });
267
406
  };
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) });
407
+ let finished = false;
408
+ const done = work()
409
+ .catch((err) => req.payload.logger.warn({ err }, 'Hats: link request not finished'))
410
+ .finally(() => {
411
+ finished = true;
412
+ });
413
+ trackWork(done);
414
+ await answer;
415
+ if (!finished)
416
+ void done.then(() => req.payload.logger.info('Hats: a link request finished after its answer. Raise linkAnswerMs if this repeats.'));
284
417
  return json({ ok: true, reason: 'linkSent', message: SENT }, 202);
285
418
  },
286
419
  };
@@ -311,15 +444,123 @@ const confirm = {
311
444
  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
445
  if (!token)
313
446
  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 });
447
+ const opts = hatsOptions(req.payload);
448
+ const hash = hashToken(token);
449
+ const thanks = () => page('Confirmed', '<p>Thanks. Once every account in the link is confirmed, an administrator reviews it. You can close this page.</p>');
450
+ // The asker confirming their own side, after the other account confirmed.
451
+ const { docs } = await req.payload.find({ collection: MEMBERS, where: { tokenHash: { equals: hash } }, limit: 1, depth: 0, overrideAccess: true, showHiddenFields: true, pagination: false, req });
315
452
  const m = docs[0];
316
- if (!m || m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
453
+ if (m) {
454
+ if (m.status !== 'requested' || !m.tokenExpires || new Date(m.tokenExpires).getTime() < Date.now())
455
+ return bad();
456
+ if ((await members(req, idOf(m.link))).length > opts.maxLinked)
457
+ return bad();
458
+ 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 }));
459
+ await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: idOf(m.link), account: idOf(m.user) });
460
+ return thanks();
461
+ }
462
+ // The invited account confirming a request. The token works once: the request is deleted before anything else.
463
+ const found = await req.payload.find({ collection: REQUESTS, where: { tokenHash: { equals: hash } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
464
+ const r = found.docs[0];
465
+ if (!r || r.account == null || new Date(r.expiresAt).getTime() < Date.now())
466
+ return bad();
467
+ let gone;
468
+ try {
469
+ gone = await asPlugin(req, () => req.payload.delete({ collection: REQUESTS, where: { and: [{ id: { equals: r.id } }, { tokenHash: { equals: hash } }] }, overrideAccess: true, req }));
470
+ }
471
+ catch {
472
+ return bad(); // the same token confirmed at the same moment: the other confirmation has it
473
+ }
474
+ if (gone.docs?.length !== 1)
475
+ return bad();
476
+ const by = idOf(r.requestedBy);
477
+ const account = idOf(r.account);
478
+ if (by === account)
479
+ return bad();
480
+ const asker = await loadUser(req, by);
481
+ const invited = await loadUser(req, account);
482
+ if (!asker || !invited || (await membershipOf(req, account)))
483
+ return bad();
484
+ const mine = await membershipOf(req, by);
485
+ const existing = mine ? idOf(mine.link) : null;
486
+ // The invitation was for the asker's set as it was then. A set the asker started since, from another of their own
487
+ // requests, is still theirs; any other change (they joined or left a set) needs a new request.
488
+ const was = r.link ? String(r.link) : null;
489
+ if (existing !== was) {
490
+ const started = was === null && existing ? (await req.payload.findByID({ collection: LINKS, id: existing, depth: 0, overrideAccess: true, disableErrors: true, req })) : null;
491
+ if (!started || idOf(started.requestedBy) !== by)
492
+ return bad();
493
+ }
494
+ if (existing && (await members(req, existing)).length + 1 > opts.maxLinked)
317
495
  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>');
496
+ const made = { rows: [] };
497
+ try {
498
+ await asPlugin(req, async () => {
499
+ const link = existing ?? String((await req.payload.create({ collection: LINKS, data: { requestedBy: relId(req.payload, opts.users, by), label: `Started by ${labelOf(asker)}` }, overrideAccess: true, req })).id);
500
+ if (!existing)
501
+ made.link = link;
502
+ const now = new Date();
503
+ const row = await req.payload.create({
504
+ collection: MEMBERS,
505
+ data: { link: relId(req.payload, LINKS, link), user: relId(req.payload, opts.users, account), status: 'confirmed', confirmedAt: now.toISOString(), addedBy: relId(req.payload, opts.users, by) },
506
+ overrideAccess: true,
507
+ req,
508
+ });
509
+ made.rows.push(String(row.id));
510
+ if (!mine) {
511
+ // The asker confirms from their own email too, now that the other account has said yes.
512
+ const own = newToken();
513
+ const hours = opts.confirmHours;
514
+ const ownRow = await req.payload.create({
515
+ collection: MEMBERS,
516
+ data: { link: relId(req.payload, LINKS, link), user: relId(req.payload, opts.users, by), status: 'requested', tokenHash: hashToken(own), tokenExpires: new Date(now.getTime() + hours * 3_600_000).toISOString(), addedBy: relId(req.payload, opts.users, by) },
517
+ overrideAccess: true,
518
+ req,
519
+ });
520
+ made.rows.push(String(ownRow.id));
521
+ made.own = own;
522
+ }
523
+ });
524
+ // The site's own callbacks run after the plugin's writes, with its mark off the request.
525
+ if (made.own) {
526
+ const own = made.own;
527
+ const hours = opts.confirmHours;
528
+ await opts.sendEmail({
529
+ payload: req.payload,
530
+ to: String(asker.email),
531
+ subject: 'Confirm linking your accounts',
532
+ text: `${labelOf(invited)} agreed to link with ${labelOf(asker)}, so one person can switch between them.\n\nConfirm from your side here within ${hours} hours:\n${await confirmLink(req, opts, own)}\n\nIf you didn’t ask for this, ignore this email: nothing is linked without it.`,
533
+ });
534
+ }
535
+ }
536
+ catch (error) {
537
+ // Someone linked one of these accounts a moment ago, or the email didn't go: undo what this made.
538
+ req.payload.logger.warn({ err: error }, 'Hats: link confirmation not recorded');
539
+ await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
540
+ for (const id of made.rows)
541
+ await removeWhere(req.payload, { collection: MEMBERS, where: { id: { equals: id } }, overrideAccess: true, req });
542
+ if (made.link)
543
+ await removeWhere(req.payload, { collection: LINKS, where: { id: { equals: made.link } }, overrideAccess: true, req });
544
+ })).catch((err) => req.payload.logger.warn({ err }, 'Hats: link confirmation clean-up skipped'));
545
+ return bad();
546
+ }
547
+ // The records are written by now, so a handler that fails can't undo or block them: it's logged and skipped.
548
+ if (made.link)
549
+ await tell(req.payload, req, { type: 'link-requested', req, link: made.link, by, account });
550
+ await tell(req.payload, req, { type: 'link-confirmed', payload: req.payload, link: existing ?? made.link, account });
551
+ return thanks();
321
552
  },
322
553
  };
554
+ /** Whether `v` is an account id written the one way the users collection writes its ids. */
555
+ function exactId(req, opts, v) {
556
+ if (typeof v !== 'string' && typeof v !== 'number')
557
+ return false;
558
+ const s = String(v);
559
+ const type = req.payload.collections[opts.users]?.customIDType ?? req.payload.db.defaultIDType;
560
+ if (type === 'number')
561
+ return /^(0|-?[1-9]\d{0,15})$/.test(s) && Number.isSafeInteger(Number(s));
562
+ return typeof v === 'string' && s.length > 0 && s.length <= 256 && s.trim() === s;
563
+ }
323
564
  /** POST /api/hats/unlink { account? }: take an account (default: the acting one) out of the set. Self-serve, at once. */
324
565
  const unlink = {
325
566
  path: '/hats/unlink',
@@ -329,14 +570,21 @@ const unlink = {
329
570
  const { opts, full, person } = await actor(req);
330
571
  await blockedReason(req, opts);
331
572
  const me = String(full.id);
332
- const account = String(req.data?.account ?? me);
573
+ const asked = req.data?.account ?? me;
574
+ const notInSet = () => refuse('That account isn’t in your linked set.', 404, 'notInSet');
575
+ // Only an id exactly as the account has it: no other spelling of a number, and nothing the database would have to
576
+ // make sense of first.
577
+ if (!exactId(req, opts, asked))
578
+ notInSet();
579
+ const account = String(asked);
333
580
  const mine = await membershipOf(req, me);
334
581
  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');
582
+ // Another account still waiting to confirm is hidden from the set, so it answers as if it weren't there.
583
+ if (!mine || !theirs || idOf(theirs.user) !== account || idOf(mine.link) !== idOf(theirs.link) || (account !== me && theirs.status === 'requested'))
584
+ notInSet();
337
585
  const link = idOf(theirs.link);
338
586
  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 });
587
+ await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: me });
340
588
  // If this session was switched in through the account just removed, it ended with the unlink.
341
589
  return json({ ok: true, signedOut: account === me ? person !== me : person === account });
342
590
  },
package/dist/index.d.ts CHANGED
@@ -1,8 +1,24 @@
1
- import type { Plugin } from 'payload';
1
+ import type { PayloadRequest, Plugin } from 'payload';
2
+ import { type SwitchInput, type SwitchResult } from './endpoints.js';
2
3
  import { type HatsOptions } from './types.js';
3
4
  export { hatsStateOf } from './state.js';
4
5
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
5
- export { LINKS, MEMBERS, SESSIONS } from './types.js';
6
+ export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
7
+ export type { SwitchInput, SwitchResult };
8
+ /**
9
+ * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
10
+ * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
11
+ * the old session's revoke), and has no option that skips one. It acts only for `req.user`: with nobody signed in it
12
+ * is refused (`signIn`, 401). It never throws for a refusal. An error from a site hook is a refusal too.
13
+ *
14
+ * On `{ ok: true }` the route must send `cookie` back as `Set-Cookie`. Call it only from a same-origin POST, never
15
+ * from a GET: a GET can be started by a link on another site, and `SameSite=Lax` still sends the sign-in cookie on it.
16
+ */
17
+ export declare const switchSession: (req: PayloadRequest, input: {
18
+ account?: string | number | null;
19
+ hat?: string;
20
+ code?: string;
21
+ }) => Promise<SwitchResult>;
6
22
  export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, StepUpContext } from './types.js';
7
23
  /**
8
24
  * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that