@extantape/payload-plugin-hats 0.6.2 → 0.8.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 +59 -3
- package/dist/approval.d.ts +26 -0
- package/dist/approval.js +48 -0
- package/dist/collections.js +17 -37
- package/dist/endpoints.d.ts +15 -0
- package/dist/endpoints.js +24 -20
- package/dist/index.d.ts +3 -7
- package/dist/index.js +20 -5
- package/dist/link.d.ts +68 -0
- package/dist/link.js +427 -0
- package/dist/sessions.js +6 -1
- package/dist/state.d.ts +14 -0
- package/dist/state.js +203 -4
- package/dist/stepup.d.ts +10 -3
- package/dist/stepup.js +21 -4
- package/dist/types.d.ts +10 -3
- package/package.json +1 -1
package/dist/state.js
CHANGED
|
@@ -106,17 +106,206 @@ export function unmarkForeignHooks(payload) {
|
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
export async function removeWhere(payload, args) {
|
|
109
|
-
|
|
109
|
+
stillInTransaction(args.req);
|
|
110
|
+
const result = (await renamed(payload.delete(args)));
|
|
110
111
|
if (result.errors?.length)
|
|
111
|
-
throw
|
|
112
|
+
throw bulkError(result.errors, `Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be removed.`);
|
|
112
113
|
return result;
|
|
113
114
|
}
|
|
114
115
|
export async function changeWhere(payload, args) {
|
|
115
|
-
|
|
116
|
+
stillInTransaction(args.req);
|
|
117
|
+
const result = (await renamed(payload.update(args)));
|
|
116
118
|
if (result.errors?.length)
|
|
117
|
-
throw
|
|
119
|
+
throw bulkError(result.errors, `Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be changed.`);
|
|
118
120
|
return result;
|
|
119
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* What the caller sees when a plugin write collided with another change to the same linked set (an account joining
|
|
124
|
+
* it while this one leaves, say): the database refused one of the two, and trying again works.
|
|
125
|
+
*/
|
|
126
|
+
export const COLLIDED = 'Hats: a linked set was being changed at the same moment, so this couldn\'t finish. Try again.';
|
|
127
|
+
const collided = (message) => message === COLLIDED || /write ?conflict|NoSuchTransaction|transaction\b[^.]*\bhas been aborted/i.test(message);
|
|
128
|
+
const messageOf = (e) => String(e?.message ?? '');
|
|
129
|
+
function bulkError(errors, plain) {
|
|
130
|
+
const messages = errors.map(messageOf);
|
|
131
|
+
// A collision says so even when later calls were then refused because it ended the transaction.
|
|
132
|
+
return new Error(messages.some(collided) ? COLLIDED : messages.includes(ENDED) ? ENDED : plain);
|
|
133
|
+
}
|
|
134
|
+
/** The write's own error, or COLLIDED in its place when the database refused it for a collision. */
|
|
135
|
+
async function renamed(write) {
|
|
136
|
+
try {
|
|
137
|
+
return await write;
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
throw collided(messageOf(error)) ? new Error(COLLIDED) : error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const holds = new AsyncLocalStorage();
|
|
144
|
+
/** Events waiting for their transaction to commit, by transaction id. */
|
|
145
|
+
const afterCommit = new Map();
|
|
146
|
+
/** Transactions rolled back lately, and the last transaction a hold saw on each request. */
|
|
147
|
+
const ended = new Set();
|
|
148
|
+
/** Transactions the database refused a write in for a collision lately. Calls refused after that say COLLIDED. */
|
|
149
|
+
const collidedIn = new Set();
|
|
150
|
+
const remember = (set, key) => {
|
|
151
|
+
set.add(key);
|
|
152
|
+
// Only the latest few matter (a bulk operation's siblings check right after); the oldest go first.
|
|
153
|
+
if (set.size > 1000)
|
|
154
|
+
set.delete(set.values().next().value);
|
|
155
|
+
};
|
|
156
|
+
/** Why a transaction ended: a collision says so, anything else is ENDED. */
|
|
157
|
+
const endedError = (tx) => new Error(tx !== undefined && collidedIn.has(tx) ? COLLIDED : ENDED);
|
|
158
|
+
const lastTx = new WeakMap();
|
|
159
|
+
// Payload leaves a promise in `transactionID` while one starts (and for good on a database without transactions). It
|
|
160
|
+
// may come from another realm, so it's recognized by its `then`, and only a string or number counts as a transaction.
|
|
161
|
+
const thenable = (t) => typeof t?.then === 'function';
|
|
162
|
+
const liveTx = (req) => {
|
|
163
|
+
const t = req.transactionID;
|
|
164
|
+
return (typeof t === 'string' && t !== '') || typeof t === 'number' ? t : undefined;
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* What the caller sees when the transaction a change ran in ended under it (another document of the same bulk delete
|
|
168
|
+
* failed, say). The plugin stops there, so nothing of its clean-up is written outside the transaction.
|
|
169
|
+
*/
|
|
170
|
+
export const ENDED = "Hats: the transaction this change ran in ended (another change in it failed), so the plugin's clean-up stopped there. Try again.";
|
|
171
|
+
/** Throws ENDED when the hold this request is in started inside a transaction that has since ended. */
|
|
172
|
+
export function stillInTransaction(req) {
|
|
173
|
+
const hold = req ? holds.getStore()?.get(req) : undefined;
|
|
174
|
+
if (req && hold?.tx !== undefined && liveTx(req) !== hold.tx)
|
|
175
|
+
throw endedError(hold.tx);
|
|
176
|
+
}
|
|
177
|
+
export async function holdEvents(req, fn) {
|
|
178
|
+
if (holds.getStore()?.has(req))
|
|
179
|
+
return await fn();
|
|
180
|
+
const raw = req.transactionID;
|
|
181
|
+
if (thenable(raw))
|
|
182
|
+
await Promise.resolve(raw).catch(() => undefined);
|
|
183
|
+
const tx = liveTx(req);
|
|
184
|
+
if (tx !== undefined)
|
|
185
|
+
lastTx.set(req, tx);
|
|
186
|
+
else {
|
|
187
|
+
// The request's transaction was rolled back before this hook started (a sibling document failed first): its
|
|
188
|
+
// clean-up would write outside any transaction, so it doesn't start.
|
|
189
|
+
const was = lastTx.get(req);
|
|
190
|
+
if (was !== undefined && ended.has(was))
|
|
191
|
+
throw endedError(was);
|
|
192
|
+
}
|
|
193
|
+
const hold = { queue: [], tx };
|
|
194
|
+
const now = new Map(holds.getStore() ?? []);
|
|
195
|
+
now.set(req, hold);
|
|
196
|
+
let result;
|
|
197
|
+
try {
|
|
198
|
+
result = await holds.run(now, fn);
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
await release(req, hold);
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
await release(req, hold);
|
|
205
|
+
return result;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Hands a hold's events on when `fn` ends, whether or not it threw: sent now without a transaction, otherwise left
|
|
209
|
+
* for the commit while the transaction is still the live one. A throw doesn't drop them by itself, because Payload
|
|
210
|
+
* doesn't always end the transaction for it (a bulk delete commits the documents that didn't fail), and what was
|
|
211
|
+
* changed before the throw is then kept.
|
|
212
|
+
*/
|
|
213
|
+
async function release(req, hold) {
|
|
214
|
+
if (hold.tx === undefined)
|
|
215
|
+
return await sendAll(req, hold.queue);
|
|
216
|
+
if (liveTx(req) !== hold.tx || !hold.queue.length)
|
|
217
|
+
return;
|
|
218
|
+
const list = afterCommit.get(hold.tx) ?? [];
|
|
219
|
+
for (const event of hold.queue.splice(0))
|
|
220
|
+
list.push({ req, event });
|
|
221
|
+
afterCommit.set(hold.tx, list);
|
|
222
|
+
}
|
|
223
|
+
async function sendAll(req, queue) {
|
|
224
|
+
for (const event of queue.splice(0))
|
|
225
|
+
await send(req.payload, req, event);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Wraps the database adapter's commit and rollback so held events follow their transaction. Payload commits and rolls
|
|
229
|
+
* back through these two methods for every operation that opens a transaction; a host transaction goes through them
|
|
230
|
+
* too when the host ends it.
|
|
231
|
+
*/
|
|
232
|
+
const WATCHED = Symbol.for('extantape.hats.transactions');
|
|
233
|
+
export function watchTransactions(payload) {
|
|
234
|
+
const db = payload.db;
|
|
235
|
+
if (db[WATCHED])
|
|
236
|
+
return;
|
|
237
|
+
db[WATCHED] = true;
|
|
238
|
+
const commit = db.commitTransaction;
|
|
239
|
+
const rollback = db.rollbackTransaction;
|
|
240
|
+
// A transaction id is a string or a number. A promise in its place (notx mode keeps one there) never held any
|
|
241
|
+
// events, so it is passed straight through: the wrapper adds no wait to a commit with nothing held.
|
|
242
|
+
const keyOf = (id) => (typeof id === 'string' && id !== '') || typeof id === 'number' ? id : undefined;
|
|
243
|
+
if (typeof commit === 'function')
|
|
244
|
+
db.commitTransaction = async function (id) {
|
|
245
|
+
const key = keyOf(id);
|
|
246
|
+
const pending = key === undefined ? undefined : afterCommit.get(key);
|
|
247
|
+
if (!pending)
|
|
248
|
+
return commit.call(this, id);
|
|
249
|
+
afterCommit.delete(key);
|
|
250
|
+
await commit.call(this, id);
|
|
251
|
+
for (const p of pending)
|
|
252
|
+
await send(payload, p.req, p.event);
|
|
253
|
+
};
|
|
254
|
+
if (typeof rollback === 'function')
|
|
255
|
+
db.rollbackTransaction = async function (id) {
|
|
256
|
+
const key = keyOf(id);
|
|
257
|
+
if (key !== undefined) {
|
|
258
|
+
afterCommit.delete(key);
|
|
259
|
+
remember(ended, key);
|
|
260
|
+
}
|
|
261
|
+
await rollback.call(this, id);
|
|
262
|
+
};
|
|
263
|
+
// Database calls made inside a hold that started in a transaction are pinned to that transaction. Payload ends a
|
|
264
|
+
// shared transaction by removing it from the adapter's open sessions and then clearing `req.transactionID`; a call
|
|
265
|
+
// that looks up its session after that (Payload's own writes for a plugin delete included) would find none, or start
|
|
266
|
+
// a new transaction, and write outside the one it belongs to. Here the call gets a request whose transaction id
|
|
267
|
+
// is read at the moment the adapter looks up its session, and refuses with ENDED when that transaction is gone, so
|
|
268
|
+
// no check-then-write gap is left.
|
|
269
|
+
const sessions = () => db.sessions;
|
|
270
|
+
const pinned = (req, tx) => Object.create(req, {
|
|
271
|
+
transactionID: {
|
|
272
|
+
enumerable: true,
|
|
273
|
+
configurable: true,
|
|
274
|
+
get() {
|
|
275
|
+
const open = sessions();
|
|
276
|
+
// An adapter without a list of open sessions can't be checked (said in the README).
|
|
277
|
+
if (!open || typeof open !== 'object')
|
|
278
|
+
return tx;
|
|
279
|
+
const session = open[String(tx)];
|
|
280
|
+
if (!session || (typeof session.inTransaction === 'function' && !session.inTransaction()))
|
|
281
|
+
throw endedError(tx);
|
|
282
|
+
return tx;
|
|
283
|
+
},
|
|
284
|
+
set() { },
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
for (const name of PINNED) {
|
|
288
|
+
const fn = db[name];
|
|
289
|
+
if (typeof fn !== 'function')
|
|
290
|
+
continue;
|
|
291
|
+
db[name] = function (args, ...rest) {
|
|
292
|
+
const req = args?.req;
|
|
293
|
+
const hold = req ? holds.getStore()?.get(req) : undefined;
|
|
294
|
+
if (!req || hold?.tx === undefined)
|
|
295
|
+
return fn.call(this, args, ...rest);
|
|
296
|
+
const tx = hold.tx;
|
|
297
|
+
const result = fn.call(this, { ...args, req: pinned(req, tx) }, ...rest);
|
|
298
|
+
// A collision ends the transaction, and the calls refused after it then report the collision too.
|
|
299
|
+
return Promise.resolve(result).catch((error) => {
|
|
300
|
+
if (collided(messageOf(error)))
|
|
301
|
+
remember(collidedIn, tx);
|
|
302
|
+
throw error;
|
|
303
|
+
});
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/** The adapter calls pinned to a hold's transaction: every read and write Payload makes for a collection. */
|
|
308
|
+
const PINNED = ['count', 'create', 'deleteMany', 'deleteOne', 'find', 'findOne', 'updateMany', 'updateOne', 'upsert'];
|
|
120
309
|
/**
|
|
121
310
|
* An id as a relationship to `slug` stores it: a number where that collection's ids are numbers (SQL adapters by
|
|
122
311
|
* default, or a custom number id), otherwise as it is. The plugin compares ids as strings, so every id it writes
|
|
@@ -171,6 +360,16 @@ export function safeName(error) {
|
|
|
171
360
|
* `TELL_MS` is left to finish unwaited, so a handler can never block or undo what already happened.
|
|
172
361
|
*/
|
|
173
362
|
export async function tell(payload, req, event) {
|
|
363
|
+
if (!hatsOptions(payload).onEvent)
|
|
364
|
+
return;
|
|
365
|
+
const hold = req ? holds.getStore()?.get(req) : undefined;
|
|
366
|
+
if (hold) {
|
|
367
|
+
hold.queue.push(event);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
await send(payload, req, event);
|
|
371
|
+
}
|
|
372
|
+
async function send(payload, req, event) {
|
|
174
373
|
const onEvent = hatsOptions(payload).onEvent;
|
|
175
374
|
if (!onEvent)
|
|
176
375
|
return;
|
package/dist/stepup.d.ts
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import type { PayloadRequest } from 'payload';
|
|
2
2
|
import type { Hat, HatsUser, ResolvedHatsOptions } from './types.js';
|
|
3
|
-
/**
|
|
4
|
-
export declare const
|
|
3
|
+
/** Every value `stepUp.rememberPer` takes. Startup refuses any other. */
|
|
4
|
+
export declare const REMEMBER_PER: readonly unknown[];
|
|
5
|
+
/**
|
|
6
|
+
* The key a good code is remembered under, or `null` when there is none to use. `'account'` (the default): the
|
|
7
|
+
* account. `'set'`: the linked set when the account is in one, else the account. `'hat'`: the account and the hat
|
|
8
|
+
* together, so an entry written under `'account'` or `'set'` never matches it. A missing hat under `'hat'`, or a
|
|
9
|
+
* value that isn't one of the three, has no key: nothing is remembered and nothing is written.
|
|
10
|
+
*/
|
|
11
|
+
export declare const memoryKey: (opts: ResolvedHatsOptions, account: string, set: string | null, hat?: string | null) => string | null;
|
|
5
12
|
/** Whether a good code was given recently enough to count. */
|
|
6
|
-
export declare const remembered: (opts: ResolvedHatsOptions, steppedUp: Record<string, string> | null | undefined, account: string, set: string | null) => boolean;
|
|
13
|
+
export declare const remembered: (opts: ResolvedHatsOptions, steppedUp: Record<string, string> | null | undefined, account: string, set: string | null, hat?: string | null) => boolean;
|
|
7
14
|
/**
|
|
8
15
|
* Does moving to `hat` on `target` need a code (before any memory is taken into account)? Without `stepUpWhen` that is
|
|
9
16
|
* the hat's `sensitive` flag. With it, the site's answer decides, and only an exact `false` skips the code: `true`, a
|
package/dist/stepup.js
CHANGED
|
@@ -1,8 +1,25 @@
|
|
|
1
|
-
/**
|
|
2
|
-
export const
|
|
1
|
+
/** Every value `stepUp.rememberPer` takes. Startup refuses any other. */
|
|
2
|
+
export const REMEMBER_PER = ['account', 'set', 'hat'];
|
|
3
|
+
/**
|
|
4
|
+
* The key a good code is remembered under, or `null` when there is none to use. `'account'` (the default): the
|
|
5
|
+
* account. `'set'`: the linked set when the account is in one, else the account. `'hat'`: the account and the hat
|
|
6
|
+
* together, so an entry written under `'account'` or `'set'` never matches it. A missing hat under `'hat'`, or a
|
|
7
|
+
* value that isn't one of the three, has no key: nothing is remembered and nothing is written.
|
|
8
|
+
*/
|
|
9
|
+
export const memoryKey = (opts, account, set, hat) => {
|
|
10
|
+
const per = opts.stepUp?.rememberPer;
|
|
11
|
+
if (per === undefined || per === 'account')
|
|
12
|
+
return account;
|
|
13
|
+
if (per === 'set')
|
|
14
|
+
return set ? `set:${set}` : account;
|
|
15
|
+
if (per === 'hat')
|
|
16
|
+
return typeof hat === 'string' && hat ? `hat:${JSON.stringify([account, hat])}` : null;
|
|
17
|
+
return null;
|
|
18
|
+
};
|
|
3
19
|
/** Whether a good code was given recently enough to count. */
|
|
4
|
-
export const remembered = (opts, steppedUp, account, set) => {
|
|
5
|
-
const
|
|
20
|
+
export const remembered = (opts, steppedUp, account, set, hat) => {
|
|
21
|
+
const key = memoryKey(opts, account, set, hat);
|
|
22
|
+
const at = key === null || !steppedUp || !Object.hasOwn(steppedUp, key) ? null : steppedUp[key];
|
|
6
23
|
return Boolean(at && Date.now() - new Date(at).getTime() < (opts.stepUp?.rememberMinutes ?? 180) * 60_000);
|
|
7
24
|
};
|
|
8
25
|
/**
|
package/dist/types.d.ts
CHANGED
|
@@ -69,10 +69,12 @@ export type HatsOptions = {
|
|
|
69
69
|
/** How long a good code is remembered, in minutes. Default 180 (three hours). */
|
|
70
70
|
rememberMinutes?: number;
|
|
71
71
|
/**
|
|
72
|
-
* What a good code is remembered for. `'account'` (default): the account it was given for. `'set'`:
|
|
73
|
-
* in the same linked set, so one two-step per person; an account in no set is still remembered on
|
|
72
|
+
* What a good code is remembered for. `'account'` (default): the account it was given for, whichever hat. `'set'`:
|
|
73
|
+
* every account in the same linked set, so one two-step per person; an account in no set is still remembered on
|
|
74
|
+
* its own. `'hat'`: that account and that hat only, so another hat on the same account asks again, and so does
|
|
75
|
+
* the same hat id on another account, linked or not. Any other value refuses to start.
|
|
74
76
|
*/
|
|
75
|
-
rememberPer?: 'account' | 'set';
|
|
77
|
+
rememberPer?: 'account' | 'set' | 'hat';
|
|
76
78
|
};
|
|
77
79
|
/**
|
|
78
80
|
* Decides whether a switch needs a code, in place of the hat's `sensitive` flag. Called with the account and hat
|
|
@@ -147,23 +149,28 @@ export type HatsOptions = {
|
|
|
147
149
|
*/
|
|
148
150
|
linkAnswerMs?: number;
|
|
149
151
|
};
|
|
152
|
+
/** `'server'` on link events from `linkAccounts` and `approveLink`. Missing on events from the endpoints and the admin form. */
|
|
153
|
+
export type LinkSource = 'server';
|
|
150
154
|
export type HatsEvent = {
|
|
151
155
|
type: 'link-requested';
|
|
152
156
|
req: PayloadRequest; /** The asker's set. When the asker had none, this fires as the set is made, just before `link-confirmed`, and `req` is the confirming request. */
|
|
153
157
|
link: string;
|
|
154
158
|
by: string;
|
|
155
159
|
account: string;
|
|
160
|
+
source?: LinkSource;
|
|
156
161
|
} | {
|
|
157
162
|
type: 'link-confirmed';
|
|
158
163
|
payload: Payload;
|
|
159
164
|
link: string;
|
|
160
165
|
account: string;
|
|
166
|
+
source?: LinkSource;
|
|
161
167
|
} | {
|
|
162
168
|
type: 'link-approved';
|
|
163
169
|
req: PayloadRequest;
|
|
164
170
|
link: string;
|
|
165
171
|
account: string;
|
|
166
172
|
by: string;
|
|
173
|
+
source?: LinkSource;
|
|
167
174
|
} | {
|
|
168
175
|
type: 'unlinked';
|
|
169
176
|
payload: Payload;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-hats",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Linked accounts and role hats for Payload: one person switches between their approved accounts, and acts in one role at a time, with a second factor before switching up.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"payload",
|