@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/accounts.js
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
import { APIError, commitTransaction, initTransaction, killTransaction } from 'payload';
|
|
2
|
+
import { exactlyTrue } from './access.js';
|
|
3
|
+
import { actor, asResult, blockedReason, labelOf, refuse } from './endpoints.js';
|
|
4
|
+
import { disabledState, exactId, loadAccount, rowOf, rowsOf } from './linking.js';
|
|
5
|
+
import { revokeSessions } from './sessions.js';
|
|
6
|
+
import { asPlugin, AuditFailed, COLLIDED, DISSOLVING, idOf, removeWhere, safeName, tell, unmarked, withMark, writeAudit } from './state.js';
|
|
7
|
+
import { LINKS, MEMBERS } from './types.js';
|
|
8
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
9
|
+
/**
|
|
10
|
+
* Whether the acting account may control other people's accounts: list their sets, take accounts out, dissolve a set,
|
|
11
|
+
* disable. Only an exact `true` from `canControlAccounts` counts. Without the option nobody may.
|
|
12
|
+
*/
|
|
13
|
+
export async function mayControl(opts, req) {
|
|
14
|
+
const ask = opts.canControlAccounts;
|
|
15
|
+
const user = req.user;
|
|
16
|
+
if (typeof ask !== 'function' || !user)
|
|
17
|
+
return false;
|
|
18
|
+
return exactlyTrue(() => unmarked(req, () => ask({ req, user })));
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Runs one change: a fresh read, the checks, the writes and the audit entries, inside a transaction where the
|
|
22
|
+
* database has them. The transaction commits only after `audit` has answered, so an entry that can't be written
|
|
23
|
+
* undoes the change. `after` runs once the change is committed (events, and sweeping up rows that arrived meanwhile).
|
|
24
|
+
* With `retry`, a transaction the database ended because another one changed the same rows first (two calls on one set
|
|
25
|
+
* at the same moment) is run again on a fresh read, so the answer names what is true by then. Any other failure is
|
|
26
|
+
* never retried: it fails the call, so a change that didn't finish is never reported as done.
|
|
27
|
+
*/
|
|
28
|
+
const collided = (error) => {
|
|
29
|
+
const e = error;
|
|
30
|
+
try {
|
|
31
|
+
// A plugin write that lost to another change to the same set already says so (state.ts renames the database's own error to COLLIDED).
|
|
32
|
+
if (e && e.message === COLLIDED)
|
|
33
|
+
return true;
|
|
34
|
+
// MongoDB's write conflict, and the serialization failure SQL databases report.
|
|
35
|
+
return Boolean(e && (e.code === 112 || e.code === '40001' || e.hasErrorLabel?.('TransientTransactionError')));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
async function change(req, retry, run) {
|
|
42
|
+
for (let attempt = 0;; attempt++) {
|
|
43
|
+
const joined = Boolean(req.transactionID);
|
|
44
|
+
const started = await initTransaction(req);
|
|
45
|
+
try {
|
|
46
|
+
const { result, after } = await run();
|
|
47
|
+
if (started)
|
|
48
|
+
await commitTransaction(req);
|
|
49
|
+
await after?.();
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
if (started)
|
|
54
|
+
await killTransaction(req);
|
|
55
|
+
// A refusal carries a reason. Any other error, one of Payload's own included, is a write that didn't go through.
|
|
56
|
+
if (error instanceof APIError && typeof error.data?.reason === 'string')
|
|
57
|
+
throw error;
|
|
58
|
+
if (error instanceof AuditFailed)
|
|
59
|
+
refuse('That couldn’t be recorded. Try again.', 500, 'auditFailed');
|
|
60
|
+
// Only a transaction started here can be run again: one the host passed in is over once a write in it fails.
|
|
61
|
+
if (!retry || !started || joined || attempt >= 2 || !collided(error))
|
|
62
|
+
throw error;
|
|
63
|
+
await sleep(25 * (attempt + 1));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The one listing, shared by GET /api/hats/accounts and `listLinkedAccounts`. Your own set is a read that is always
|
|
69
|
+
* open, so `blocked` isn't asked. Another account's set (`of`) is for a controller only, and `blocked` is asked with
|
|
70
|
+
* `list` first.
|
|
71
|
+
*/
|
|
72
|
+
export const runList = (req, input) => asResult(req, 'a listing', () => listCore(req, input ?? {}));
|
|
73
|
+
async function listCore(req, input) {
|
|
74
|
+
const { opts, full } = await actor(req, 401);
|
|
75
|
+
const p = req.payload;
|
|
76
|
+
const me = String(full.id);
|
|
77
|
+
const own = input.of == null || (exactId(p, opts, input.of) && String(input.of) === me);
|
|
78
|
+
let subject = full;
|
|
79
|
+
if (!own) {
|
|
80
|
+
await blockedReason(req, opts, 'list');
|
|
81
|
+
if (!(await mayControl(opts, req)))
|
|
82
|
+
refuse('You can’t see another account’s linked accounts.', 403, 'notAllowed');
|
|
83
|
+
const found = exactId(p, opts, input.of) ? await loadAccount(p, String(input.of), req) : null;
|
|
84
|
+
if (!found)
|
|
85
|
+
refuse('That account doesn’t exist.', 404, 'notFound');
|
|
86
|
+
subject = found;
|
|
87
|
+
}
|
|
88
|
+
const mine = await rowOf(p, String(subject.id), req);
|
|
89
|
+
const accounts = [];
|
|
90
|
+
if (!mine)
|
|
91
|
+
return { ok: true, set: null, accounts: [{ id: subject.id, label: labelOf(subject), you: String(subject.id) === me }], maxLinked: opts.maxLinked };
|
|
92
|
+
// The account asked about comes first, then the others in the order they joined.
|
|
93
|
+
const when = (r) => String(r.createdAt ?? '');
|
|
94
|
+
const rows = (await rowsOf(p, idOf(mine.link), req)).sort((x, y) => when(x).localeCompare(when(y)) || String(x.id).localeCompare(String(y.id)));
|
|
95
|
+
for (const m of [...rows.filter((r) => idOf(r.user) === String(subject.id)), ...rows.filter((r) => idOf(r.user) !== String(subject.id))]) {
|
|
96
|
+
if (m.user == null)
|
|
97
|
+
continue;
|
|
98
|
+
const id = idOf(m.user);
|
|
99
|
+
const isSubject = id === String(subject.id);
|
|
100
|
+
// A person sees themselves and the approved accounts. An account still waiting stays hidden, so a request never
|
|
101
|
+
// shows whether an address has an account here. A controller sees every row, with emails for approved ones only.
|
|
102
|
+
if (own && !isSubject && m.status !== 'approved')
|
|
103
|
+
continue;
|
|
104
|
+
const u = isSubject ? subject : await loadAccount(p, id, req);
|
|
105
|
+
if (!u)
|
|
106
|
+
continue;
|
|
107
|
+
accounts.push({ id: u.id, label: m.status === 'approved' || (own && isSubject) ? labelOf(u) : String(u.id), you: id === me, status: m.status });
|
|
108
|
+
}
|
|
109
|
+
return { ok: true, set: idOf(mine.link), accounts, maxLinked: opts.maxLinked };
|
|
110
|
+
}
|
|
111
|
+
/** The one unlink, shared by POST /api/hats/unlink and `unlinkAccount`. */
|
|
112
|
+
export const runUnlink = (req, input) => asResult(req, 'an unlink', () => unlinkCore(req, input ?? {}));
|
|
113
|
+
async function unlinkCore(req, input) {
|
|
114
|
+
const { opts, full, state, person } = await actor(req, 401);
|
|
115
|
+
await blockedReason(req, opts, 'unlink');
|
|
116
|
+
const p = req.payload;
|
|
117
|
+
const me = String(full.id);
|
|
118
|
+
const asked = input.account ?? me;
|
|
119
|
+
const notInSet = () => refuse('That account isn’t in your linked set.', 404, 'notInSet');
|
|
120
|
+
// Only an id exactly as the account has it: no other spelling of a number, and nothing the database would have to
|
|
121
|
+
// make sense of first.
|
|
122
|
+
if (!exactId(p, opts, asked))
|
|
123
|
+
notInSet();
|
|
124
|
+
const account = String(asked);
|
|
125
|
+
return change(req, true, async () => {
|
|
126
|
+
const mine = await rowOf(p, me, req);
|
|
127
|
+
const theirs = account === me ? mine : await rowOf(p, account, req);
|
|
128
|
+
if (account === me) {
|
|
129
|
+
// Leaving is always open, whatever the account's status or the host's word on who may be linked.
|
|
130
|
+
if (!mine)
|
|
131
|
+
notInSet();
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
// Another account still waiting to confirm is hidden from the set, so it answers as if it weren't there.
|
|
135
|
+
const seen = Boolean(mine && theirs && idOf(mine.link) === idOf(theirs.link) && theirs.status !== 'requested');
|
|
136
|
+
// An approved account may take another out. While nobody in the set is approved yet, any account in it may.
|
|
137
|
+
const member = seen && (mine.status === 'approved' || !(await rowsOf(p, idOf(mine.link), req)).some((r) => r.status === 'approved'));
|
|
138
|
+
if (!member) {
|
|
139
|
+
if (!(await mayControl(opts, req))) {
|
|
140
|
+
if (seen)
|
|
141
|
+
refuse('Only an approved account in the set can take another account out.', 403, 'notAllowed');
|
|
142
|
+
notInSet();
|
|
143
|
+
}
|
|
144
|
+
if (!theirs)
|
|
145
|
+
notInSet();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const link = idOf(theirs.link);
|
|
149
|
+
try {
|
|
150
|
+
await asPlugin(req, () => p.delete({ collection: MEMBERS, id: theirs.id, overrideAccess: true, req }));
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
// The row went between the read and the delete: someone else took the account out a moment ago. Payload
|
|
154
|
+
// answers that with a 404, or, when the row goes after it was found, with a TypeError from reading a row that
|
|
155
|
+
// came back empty. Any other error is a write that failed, and fails the call.
|
|
156
|
+
const gone = (error instanceof APIError && error.status === 404) || error instanceof TypeError;
|
|
157
|
+
if (gone && !(await rowOf(p, account, req)))
|
|
158
|
+
notInSet();
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
await writeAudit(p, req, [{ action: 'unlinked', actor: me, account, via: state.via, hat: state.hat, reason: null }]);
|
|
162
|
+
return {
|
|
163
|
+
// If this session was switched in through the account just removed, it ended with the unlink.
|
|
164
|
+
result: { ok: true, account, signedOut: account === me ? person !== me : person === account },
|
|
165
|
+
after: () => tell(p, req, { type: 'unlinked', payload: p, link, account, by: me }),
|
|
166
|
+
};
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Removes every row of a set, then the set. Rows go one at a time under the dissolving mark, so each row's own
|
|
171
|
+
* clean-up ends the sessions switched through it without trying to dissolve the set again.
|
|
172
|
+
*/
|
|
173
|
+
async function removeSet(req, link) {
|
|
174
|
+
const p = req.payload;
|
|
175
|
+
const gone = [];
|
|
176
|
+
await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
|
|
177
|
+
for (const r of await rowsOf(p, link, req)) {
|
|
178
|
+
const { docs } = await removeWhere(p, { collection: MEMBERS, where: { id: { equals: r.id } }, overrideAccess: true, req });
|
|
179
|
+
if (docs.length)
|
|
180
|
+
gone.push(r);
|
|
181
|
+
}
|
|
182
|
+
await removeWhere(p, { collection: LINKS, where: { id: { equals: link } }, overrideAccess: true, req });
|
|
183
|
+
}));
|
|
184
|
+
await revokeSessions(p, { link: { equals: link } }, 'set dissolved', req);
|
|
185
|
+
return gone;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* After a set is gone for good: a confirmation or a trusted link that read the set a moment before can still have
|
|
189
|
+
* written a row into it. Such a row is removed here, once the dissolve is committed, so no account is left in a set
|
|
190
|
+
* that doesn't exist. (The other side checks too: a link that finds its set gone takes its own rows back.)
|
|
191
|
+
*/
|
|
192
|
+
async function sweepSet(req, link) {
|
|
193
|
+
const p = req.payload;
|
|
194
|
+
const gone = [];
|
|
195
|
+
try {
|
|
196
|
+
await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
|
|
197
|
+
for (const r of await rowsOf(p, link, req)) {
|
|
198
|
+
await removeWhere(p, { collection: MEMBERS, where: { id: { equals: r.id } }, overrideAccess: true, req });
|
|
199
|
+
gone.push(r);
|
|
200
|
+
}
|
|
201
|
+
}));
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
p.logger.warn({ err }, 'Hats: rows that arrived while a set was dissolving were not removed');
|
|
205
|
+
}
|
|
206
|
+
return gone;
|
|
207
|
+
}
|
|
208
|
+
/** The one decouple, shared by POST /api/hats/decouple and `decouple`. */
|
|
209
|
+
export const runDecouple = (req, input) => asResult(req, 'a decouple', () => decoupleCore(req, input ?? {}));
|
|
210
|
+
async function decoupleCore(req, input) {
|
|
211
|
+
const { opts, full, state } = await actor(req, 401);
|
|
212
|
+
await blockedReason(req, opts, 'decouple');
|
|
213
|
+
const p = req.payload;
|
|
214
|
+
const me = String(full.id);
|
|
215
|
+
const asked = input.account ?? me;
|
|
216
|
+
const notInSet = () => refuse('That account isn’t in a linked set.', 404, 'notInSet');
|
|
217
|
+
if (!exactId(p, opts, asked))
|
|
218
|
+
notInSet();
|
|
219
|
+
const account = String(asked);
|
|
220
|
+
return change(req, true, async () => {
|
|
221
|
+
const mine = await rowOf(p, me, req);
|
|
222
|
+
const theirs = account === me ? mine : await rowOf(p, account, req);
|
|
223
|
+
// The same view as unlinking: another account still waiting to confirm answers as if it weren't there.
|
|
224
|
+
const seen = Boolean(mine && theirs && idOf(mine.link) === idOf(theirs.link) && (account === me || theirs.status !== 'requested'));
|
|
225
|
+
let controller = false;
|
|
226
|
+
if (!(seen && mine.status === 'approved')) {
|
|
227
|
+
controller = await mayControl(opts, req);
|
|
228
|
+
if (!controller) {
|
|
229
|
+
if (seen)
|
|
230
|
+
refuse('Only an approved account in the set can unlink every account.', 403, 'notAllowed');
|
|
231
|
+
notInSet();
|
|
232
|
+
}
|
|
233
|
+
if (!theirs)
|
|
234
|
+
notInSet();
|
|
235
|
+
}
|
|
236
|
+
const link = idOf(theirs.link);
|
|
237
|
+
const gone = await removeSet(req, link);
|
|
238
|
+
// Someone else dissolved it a moment ago: there was nothing left for this call to take apart.
|
|
239
|
+
if (!gone.length)
|
|
240
|
+
notInSet();
|
|
241
|
+
const accounts = gone.filter((r) => r.user != null).map((r) => idOf(r.user));
|
|
242
|
+
await writeAudit(p, req, accounts.map((a) => ({ action: 'decoupled', actor: me, account: a, via: state.via, hat: state.hat, reason: null })));
|
|
243
|
+
return {
|
|
244
|
+
result: {
|
|
245
|
+
ok: true,
|
|
246
|
+
unlinked: gone.filter((r) => r.user != null && (controller || r.status !== 'requested' || idOf(r.user) === me)).map((r) => idOf(r.user)),
|
|
247
|
+
signedOut: state.link === link,
|
|
248
|
+
},
|
|
249
|
+
after: async () => {
|
|
250
|
+
await sweepSet(req, link);
|
|
251
|
+
await tell(p, req, { type: 'decoupled', payload: p, link, accounts, by: me });
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
/** The one disable, shared by `disableAccount` and `disableAll`. No endpoint reaches it: the host calls it from its own route. */
|
|
257
|
+
export const runDisable = (req, input, all) => asResult(req, 'a disable', () => disableCore(req, (input ?? {}), all));
|
|
258
|
+
async function disableCore(req, input, all) {
|
|
259
|
+
const { opts, full, state, person } = await actor(req, 401);
|
|
260
|
+
await blockedReason(req, opts, 'disable');
|
|
261
|
+
if (!(await mayControl(opts, req)))
|
|
262
|
+
refuse('You can’t disable accounts.', 403, 'notAllowed');
|
|
263
|
+
const apply = opts.disable?.apply;
|
|
264
|
+
if (typeof apply !== 'function' || typeof opts.disable?.isDisabled !== 'function')
|
|
265
|
+
refuse('Disabling accounts isn’t turned on here.', 403, 'disableOff');
|
|
266
|
+
const p = req.payload;
|
|
267
|
+
const me = String(full.id);
|
|
268
|
+
const notFound = () => refuse('That account doesn’t exist.', 404, 'notFound');
|
|
269
|
+
if (!exactId(p, opts, input.account))
|
|
270
|
+
notFound();
|
|
271
|
+
const reason = typeof input.reason === 'string' && input.reason.trim() ? input.reason.trim() : null;
|
|
272
|
+
// Only an exact `true` unlinks, and anything but a missing or `false` dryRun writes nothing: an unclear value does less.
|
|
273
|
+
const unlink = input.decouple === true;
|
|
274
|
+
const dry = input.dryRun !== undefined && input.dryRun !== false;
|
|
275
|
+
const handled = new Set();
|
|
276
|
+
const disabled = [];
|
|
277
|
+
const skipped = [];
|
|
278
|
+
/** Rows this call took out, so an account approved into the set while it ran can still be found afterwards. */
|
|
279
|
+
const removed = [];
|
|
280
|
+
let set = null;
|
|
281
|
+
let dissolved = false;
|
|
282
|
+
const entry = { actor: me, via: state.via, hat: state.hat, reason };
|
|
283
|
+
/** Every check on a batch of accounts first, then the writes. A refusal here stops the whole call. */
|
|
284
|
+
const round = async (accounts) => {
|
|
285
|
+
for (const a of accounts)
|
|
286
|
+
if (String(a.id) === me || String(a.id) === person)
|
|
287
|
+
refuse('You can’t disable the account you’re signed in with.', 403, 'cannotDisableSelf');
|
|
288
|
+
const protect = opts.disable?.protect;
|
|
289
|
+
if (protect)
|
|
290
|
+
for (const a of accounts) {
|
|
291
|
+
// Only an exact `false` leaves an account unprotected: a throw or any other answer keeps it safe.
|
|
292
|
+
let open = false;
|
|
293
|
+
try {
|
|
294
|
+
open = (await unmarked(req, () => protect({ req, actor: full, account: a }))) === false;
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
open = false;
|
|
298
|
+
}
|
|
299
|
+
if (!open)
|
|
300
|
+
refuse('That account is protected and can’t be disabled here.', 403, 'protectedAccount');
|
|
301
|
+
}
|
|
302
|
+
const todo = [];
|
|
303
|
+
for (const a of accounts) {
|
|
304
|
+
handled.add(String(a.id));
|
|
305
|
+
// Only an exact `true` skips. An answer that isn't clear gets `apply` again, which is the safe way round.
|
|
306
|
+
if ((await disabledState(opts, req, a)) === 'yes')
|
|
307
|
+
skipped.push(String(a.id));
|
|
308
|
+
else
|
|
309
|
+
todo.push(a);
|
|
310
|
+
}
|
|
311
|
+
if (dry)
|
|
312
|
+
return void disabled.push(...todo.map((a) => String(a.id)));
|
|
313
|
+
for (const a of todo) {
|
|
314
|
+
try {
|
|
315
|
+
await unmarked(req, () => apply({ req, account: a, reason }));
|
|
316
|
+
}
|
|
317
|
+
catch (error) {
|
|
318
|
+
p.logger.error({ msg: `Hats: disable.apply failed (${safeName(error)})` });
|
|
319
|
+
refuse('Disabling didn’t finish. Run it again.', 500, 'failed');
|
|
320
|
+
}
|
|
321
|
+
disabled.push(String(a.id));
|
|
322
|
+
}
|
|
323
|
+
// Every session switched into or through these accounts ends, along with any the plugin keeps a record for.
|
|
324
|
+
const ids = accounts.map((a) => String(a.id));
|
|
325
|
+
await revokeSessions(p, { or: [{ user: { in: ids } }, { via: { in: ids } }] }, 'account disabled', req);
|
|
326
|
+
};
|
|
327
|
+
/** Approved accounts no round has handled yet: in the set as it is now, and among the rows this call took out. */
|
|
328
|
+
const approvedLeft = async () => {
|
|
329
|
+
const rows = [...(set !== null && !dissolved ? await rowsOf(p, set, req) : []), ...removed];
|
|
330
|
+
const out = [];
|
|
331
|
+
for (const r of rows) {
|
|
332
|
+
if (r.user == null || r.status !== 'approved' || handled.has(idOf(r.user)) || out.some((u) => String(u.id) === idOf(r.user)))
|
|
333
|
+
continue;
|
|
334
|
+
const u = await loadAccount(p, idOf(r.user), req);
|
|
335
|
+
if (u)
|
|
336
|
+
out.push(u);
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
};
|
|
340
|
+
const result = await change(req, false, async () => {
|
|
341
|
+
const named = await loadAccount(p, String(input.account), req);
|
|
342
|
+
if (!named)
|
|
343
|
+
notFound();
|
|
344
|
+
const row = await rowOf(p, String(named.id), req);
|
|
345
|
+
// A link nobody approved isn't a link yet, so an account waiting in a set is disabled on its own.
|
|
346
|
+
set = all && row?.status === 'approved' ? idOf(row.link) : null;
|
|
347
|
+
await round([named, ...(await approvedLeft()).filter((u) => String(u.id) !== String(named.id))]);
|
|
348
|
+
const link = row ? idOf(row.link) : null;
|
|
349
|
+
const before = row && link && unlink ? await rowsOf(p, link, req) : [];
|
|
350
|
+
if (dry) {
|
|
351
|
+
// What a real run would take out: the whole set for `disableAll`, the one account otherwise (and the last one
|
|
352
|
+
// left with it, since a set of one isn't a link).
|
|
353
|
+
const out = set !== null || before.length <= 2 ? before : before.filter((r) => idOf(r.user) === String(named.id));
|
|
354
|
+
return { result: { ok: true, disabled, skipped, unlinked: out.filter((r) => r.user != null).map((r) => idOf(r.user)) } };
|
|
355
|
+
}
|
|
356
|
+
let unlinked = [];
|
|
357
|
+
if (unlink && row && link) {
|
|
358
|
+
if (set !== null) {
|
|
359
|
+
removed.push(...(await removeSet(req, link)));
|
|
360
|
+
dissolved = true;
|
|
361
|
+
unlinked = removed.filter((r) => r.user != null).map((r) => idOf(r.user));
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
await asPlugin(req, () => p.delete({ collection: MEMBERS, id: row.id, overrideAccess: true, req }));
|
|
365
|
+
const left = new Set((await rowsOf(p, link, req)).map((r) => idOf(r.user)));
|
|
366
|
+
unlinked = before.filter((r) => r.user != null && !left.has(idOf(r.user))).map((r) => idOf(r.user));
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
await writeAudit(p, req, [...disabled.map((a) => ({ action: 'disabled', account: a, ...entry })), ...unlinked.map((a) => ({ action: 'decoupled', account: a, ...entry }))]);
|
|
370
|
+
const told = [...disabled];
|
|
371
|
+
return {
|
|
372
|
+
result: { ok: true, disabled, skipped, unlinked },
|
|
373
|
+
after: async () => {
|
|
374
|
+
if (dissolved && link) {
|
|
375
|
+
const late = await sweepSet(req, link);
|
|
376
|
+
removed.push(...late);
|
|
377
|
+
unlinked.push(...late.filter((r) => r.user != null).map((r) => idOf(r.user)));
|
|
378
|
+
}
|
|
379
|
+
if (told.length)
|
|
380
|
+
await tell(p, req, { type: 'accounts-disabled', payload: p, accounts: told, by: me, reason });
|
|
381
|
+
if (unlinked.length && link)
|
|
382
|
+
await tell(p, req, { type: 'decoupled', payload: p, link, accounts: unlinked, by: me });
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
if (dry)
|
|
387
|
+
return result;
|
|
388
|
+
// An account approved into the set while this ran is disabled too, so none is missed. One that can't be (the
|
|
389
|
+
// acting account, a protected one) refuses the call, which says so instead of passing over it.
|
|
390
|
+
for (let pass = 0; pass < 3; pass++) {
|
|
391
|
+
const late = await approvedLeft();
|
|
392
|
+
if (!late.length)
|
|
393
|
+
break;
|
|
394
|
+
const from = disabled.length;
|
|
395
|
+
await change(req, false, async () => {
|
|
396
|
+
await round(late);
|
|
397
|
+
const fresh = disabled.slice(from);
|
|
398
|
+
await writeAudit(p, req, fresh.map((a) => ({ action: 'disabled', account: a, ...entry })));
|
|
399
|
+
return { result: null, after: async () => void (fresh.length && (await tell(p, req, { type: 'accounts-disabled', payload: p, accounts: fresh, by: me, reason }))) };
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return result;
|
|
403
|
+
}
|
package/dist/approval.d.ts
CHANGED
|
@@ -10,6 +10,12 @@ export type ApprovalRefusal = {
|
|
|
10
10
|
* `canApproveLinks` answering exactly `true`. A truthy value or a thrown error is a no.
|
|
11
11
|
*/
|
|
12
12
|
export declare function isApprover(opts: ResolvedHatsOptions, req: PayloadRequest): Promise<boolean>;
|
|
13
|
+
/**
|
|
14
|
+
* In a switched session the person who first signed in is the one acting. They must still be someone the host lets be
|
|
15
|
+
* linked and who isn't disabled, as everywhere else in a switched session. Anything unclear is a no. True when the
|
|
16
|
+
* session isn't switched.
|
|
17
|
+
*/
|
|
18
|
+
export declare function firstSignerStands(opts: ResolvedHatsOptions, req: PayloadRequest): Promise<boolean>;
|
|
13
19
|
/**
|
|
14
20
|
* The one approval rule. The approver is `req.user`, never an id passed in. It's refused when:
|
|
15
21
|
* - `req.user` isn't an approver (`notApprover`);
|
package/dist/approval.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { exactlyTrue } from './access.js';
|
|
2
|
+
import { disabledState, loadAccount, mayBeLinked } from './linking.js';
|
|
2
3
|
import { hatsStateOf } from './state.js';
|
|
3
4
|
import { MEMBERS } from './types.js';
|
|
4
5
|
/**
|
|
@@ -12,6 +13,19 @@ export async function isApprover(opts, req) {
|
|
|
12
13
|
const ask = opts.canApproveLinks;
|
|
13
14
|
return exactlyTrue(() => ask({ req, user }));
|
|
14
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* In a switched session the person who first signed in is the one acting. They must still be someone the host lets be
|
|
18
|
+
* linked and who isn't disabled, as everywhere else in a switched session. Anything unclear is a no. True when the
|
|
19
|
+
* session isn't switched.
|
|
20
|
+
*/
|
|
21
|
+
export async function firstSignerStands(opts, req) {
|
|
22
|
+
const me = req.user;
|
|
23
|
+
const via = me ? hatsStateOf(me)?.via : undefined;
|
|
24
|
+
if (via == null || String(via) === String(me.id))
|
|
25
|
+
return true;
|
|
26
|
+
const first = await loadAccount(req.payload, String(via), req);
|
|
27
|
+
return !!first && (await disabledState(opts, req, first)) === 'no' && (await mayBeLinked(opts, req, first));
|
|
28
|
+
}
|
|
15
29
|
/**
|
|
16
30
|
* The one approval rule. The approver is `req.user`, never an id passed in. It's refused when:
|
|
17
31
|
* - `req.user` isn't an approver (`notApprover`);
|
|
@@ -24,6 +38,8 @@ export async function approvalRefusal(req, opts, args) {
|
|
|
24
38
|
if (!(await isApprover(opts, req)))
|
|
25
39
|
return { reason: 'notApprover', message: 'You can’t approve links.' };
|
|
26
40
|
const me = req.user;
|
|
41
|
+
if (!(await firstSignerStands(opts, req)))
|
|
42
|
+
return { reason: 'notApprover', message: 'You can’t approve links.' };
|
|
27
43
|
const people = [String(me.id), hatsStateOf(me)?.via].filter(Boolean);
|
|
28
44
|
const ownSet = { reason: 'ownSet', message: 'You can’t approve a set you belong to. Ask another administrator.' };
|
|
29
45
|
if ((args.joining ?? []).some((j) => people.includes(j)))
|
package/dist/collections.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { APIError, validations } from 'payload';
|
|
2
|
-
import { approvalRefusal, isApprover } from './approval.js';
|
|
2
|
+
import { approvalRefusal, firstSignerStands, isApprover } from './approval.js';
|
|
3
|
+
import { checkLink, loadAccount } from './linking.js';
|
|
3
4
|
import { dissolveIfAlone, revokeSessions } from './sessions.js';
|
|
4
5
|
import { holdEvents, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
|
|
5
6
|
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
@@ -22,7 +23,9 @@ const approver = isApprover;
|
|
|
22
23
|
/** The admin form's statuses for each refusal, as before `approveLink` shared the rule. */
|
|
23
24
|
const HOOK_STATUS = { notApprover: 403, ownSet: 403, setFull: 400 };
|
|
24
25
|
export function hatCollections(opts, sql) {
|
|
25
|
-
|
|
26
|
+
// Reading, updating and deleting rows also need the first signer to stand, so a switched session can't do through the
|
|
27
|
+
// collections what the plugin's own endpoints refuse it.
|
|
28
|
+
const canApprove = async ({ req }) => (await approver(opts, req)) && (await firstSignerStands(opts, req));
|
|
26
29
|
const never = () => false;
|
|
27
30
|
const links = {
|
|
28
31
|
slug: LINKS,
|
|
@@ -87,6 +90,14 @@ export function hatCollections(opts, sql) {
|
|
|
87
90
|
const refused = await approvalRefusal(req, opts, { link: idOf(originalDoc.link), approving: 1, except: String(originalDoc.id) });
|
|
88
91
|
if (refused)
|
|
89
92
|
throw new APIError(refused.message, HOOK_STATUS[refused.reason], undefined, true);
|
|
93
|
+
// The host's own rules hold at approval too, whatever happened before: the account still has to be one that
|
|
94
|
+
// may be linked and isn't disabled.
|
|
95
|
+
const account = originalDoc.user == null ? null : await loadAccount(req.payload, idOf(originalDoc.user), req);
|
|
96
|
+
if (!account)
|
|
97
|
+
throw new APIError('That account no longer exists.', 400, undefined, true);
|
|
98
|
+
const check = await checkLink(req.payload, opts, { req, set: idOf(originalDoc.link), members: [account], joining: [], count: 'approved' });
|
|
99
|
+
if (!check.ok)
|
|
100
|
+
throw new APIError(check.message, check.status, { reason: check.reason }, true);
|
|
90
101
|
return { ...data, approvedBy: req.user.id, approvedAt: new Date().toISOString() };
|
|
91
102
|
}),
|
|
92
103
|
],
|
package/dist/endpoints.d.ts
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { type Endpoint, type PayloadRequest } from 'payload';
|
|
2
2
|
import { revokeSessions } from './sessions.js';
|
|
3
|
-
import { type Hat, type HatsUser, type ResolvedHatsOptions } from './types.js';
|
|
3
|
+
import { type Hat, type HatsAction, type HatsUser, type Refusal, type ResolvedHatsOptions } from './types.js';
|
|
4
|
+
/** A refusal with a stable `reason`, so a site can show its own words for it (the English message is the fallback). */
|
|
5
|
+
export declare const refuse: (message: string, status?: number, reason?: string) => never;
|
|
6
|
+
/** The acting account, its full record (all roles, not the hat), and the session's hat state. */
|
|
7
|
+
export declare function actor(req: PayloadRequest, noSession?: number, checkFirst?: boolean): Promise<{
|
|
8
|
+
opts: ResolvedHatsOptions;
|
|
9
|
+
user: HatsUser;
|
|
10
|
+
full: HatsUser;
|
|
11
|
+
state: import("./types.js").HatsState;
|
|
12
|
+
person: string;
|
|
13
|
+
}>;
|
|
4
14
|
export declare const loadUser: (req: PayloadRequest, id: string) => Promise<HatsUser | null>;
|
|
5
15
|
export declare const labelOf: (u: HatsUser) => string;
|
|
6
16
|
export declare function members(req: PayloadRequest, link: string): Promise<{
|
|
@@ -28,6 +38,7 @@ export declare function showsSwitch(opts: ResolvedHatsOptions, args: {
|
|
|
28
38
|
hats: Hat[];
|
|
29
39
|
}[];
|
|
30
40
|
}, worn: string | null): boolean;
|
|
41
|
+
export declare function blockedReason(req: PayloadRequest, opts: ResolvedHatsOptions, action: HatsAction): Promise<void>;
|
|
31
42
|
/** What a switch came to. A refusal carries the endpoint's `reason` (`needsCode` included) and its English message. */
|
|
32
43
|
export type SwitchResult = {
|
|
33
44
|
ok: true;
|
|
@@ -51,6 +62,28 @@ export type SwitchInput = {
|
|
|
51
62
|
* `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
|
|
52
63
|
*/
|
|
53
64
|
export declare function runSwitch(req: PayloadRequest, input: SwitchInput | null | undefined): Promise<SwitchResult>;
|
|
65
|
+
/**
|
|
66
|
+
* What Payload's own login would turn an account away for: a lock that hasn't run out, or an email not yet confirmed
|
|
67
|
+
* when the collection verifies emails. The switch and `accountToSignIn` both read it here, so they can't drift.
|
|
68
|
+
*/
|
|
69
|
+
export declare function loginBar(payload: PayloadRequest['payload'], opts: ResolvedHatsOptions, account: HatsUser): 'locked' | 'unverified' | null;
|
|
70
|
+
/** What a link request came to. The answer is the same whatever the address, so it says nothing about it. */
|
|
71
|
+
export type LinkRequestResult = {
|
|
72
|
+
ok: true;
|
|
73
|
+
reason: 'linkSent';
|
|
74
|
+
message: string;
|
|
75
|
+
} | Refusal;
|
|
76
|
+
/** Turns the refusals a core throws into a result, so the exported functions never throw for one. */
|
|
77
|
+
export declare function asResult<T extends {
|
|
78
|
+
ok: true;
|
|
79
|
+
}>(req: PayloadRequest, what: string, run: () => Promise<T>): Promise<T | Refusal>;
|
|
80
|
+
/**
|
|
81
|
+
* The one link request, shared by POST /api/hats/link and `requestLink`. It acts only for `req.user`, has no option
|
|
82
|
+
* that skips a check, and never throws for a refusal.
|
|
83
|
+
*/
|
|
84
|
+
export declare const runRequestLink: (req: PayloadRequest, input: {
|
|
85
|
+
email?: unknown;
|
|
86
|
+
} | null | undefined) => Promise<LinkRequestResult>;
|
|
54
87
|
/** Whether `v` is an account id written the one way the users collection writes its ids. */
|
|
55
88
|
export declare function exactId(req: PayloadRequest, opts: ResolvedHatsOptions, v: unknown): boolean;
|
|
56
89
|
export declare const hatEndpoints: Endpoint[];
|