@extantape/payload-plugin-masq 0.1.1 → 0.1.2
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 +27 -6
- package/dist/endpoints.js +7 -3
- package/dist/index.d.ts +1 -1
- package/dist/plugin.js +26 -2
- package/dist/recheck.d.ts +11 -0
- package/dist/recheck.js +136 -0
- package/dist/state.d.ts +28 -1
- package/dist/state.js +72 -15
- package/dist/types.d.ts +19 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Masquerade for [Payload](https://payloadcms.com) 3: an admin signs in as another
|
|
|
4
4
|
the site and admin exactly as they do, then returns to their own account with one click.
|
|
5
5
|
Built for support and troubleshooting.
|
|
6
6
|
|
|
7
|
-
> **Beta (0.x).** Used in production
|
|
7
|
+
> **Beta (0.x).** Used in production on a live site. Feedback and issues welcome.
|
|
8
8
|
|
|
9
9
|
## What you get
|
|
10
10
|
|
|
@@ -44,6 +44,21 @@ Built for support and troubleshooting.
|
|
|
44
44
|
account** in the banner to clear it, or wait for the cookie to expire.
|
|
45
45
|
- **`canMasquerade` must answer exactly `true`.** A truthy value, or an error it throws, is a
|
|
46
46
|
no: the endpoints answer 403 and the components show nothing.
|
|
47
|
+
- **Checked on every request.** While a borrowed session is live, every request that carries
|
|
48
|
+
its token, in the cookie or an `Authorization` header, asks `canMasquerade` again with the
|
|
49
|
+
masquerader and the target loaded fresh, then your `recheck` if you set one. If the answer
|
|
50
|
+
is no (the masquerader was demoted or deleted, or the target changed so the rule refuses),
|
|
51
|
+
the borrowed session is deleted on that request, the request runs signed out, and `onStop`
|
|
52
|
+
gets `revoked: true`. If the check itself fails (a read or the delete throws), the borrowed
|
|
53
|
+
token is ignored for that request, so it runs signed out. The cost is two reads by ID on
|
|
54
|
+
requests that carry a borrowed token, and nothing on any other request.
|
|
55
|
+
- **Limits of the check.** It is an auth strategy that Masq puts first on its collection, so an
|
|
56
|
+
auth collection listed before it, or a strategy another plugin puts in front later, runs
|
|
57
|
+
before it. Signing the masquerader out everywhere doesn't end a borrowed session; if that
|
|
58
|
+
should end it, check it in `recheck`. `recheck` runs before anyone is signed in, so
|
|
59
|
+
`req.user` isn't set yet; use the `masquerader` and `target` it gets. The token is read from
|
|
60
|
+
the cookie even on cross-site requests, the same as Payload's own sign-in. Behind a Next.js
|
|
61
|
+
`basePath`, stopping a revoked masquerade can report `onStop` twice.
|
|
47
62
|
- Never as yourself, no nesting, no public endpoints: masquerading needs a signed-in user the
|
|
48
63
|
rules allow.
|
|
49
64
|
|
|
@@ -69,12 +84,17 @@ Or on MongoDB from the command line (the same change, not tested here):
|
|
|
69
84
|
mongosh "$DATABASE_URI" --eval 'db.users.updateMany({}, { $set: { sessions: [] } })'
|
|
70
85
|
```
|
|
71
86
|
|
|
72
|
-
|
|
73
|
-
|
|
87
|
+
From 0.1.2, Masq needs `useSessions` left out or set to `true` on its auth collection, because it
|
|
88
|
+
ends a borrowed token by deleting its session. Any other value (`false`, `0`, an empty string)
|
|
89
|
+
stops the build. It checks again when Payload starts, so a plugin listed after Masq or a change
|
|
90
|
+
to the built config that turns sessions off stops start-up too. If sessions are off anyway, for
|
|
91
|
+
example when start-up checks were skipped, no borrowed token signs anyone in and no masquerade
|
|
92
|
+
can start. If you ran 0.1.0 or 0.1.1 that way, changing
|
|
93
|
+
`PAYLOAD_SECRET` is the only way to end the old tokens, and it signs everyone out.
|
|
74
94
|
|
|
75
95
|
## On its own, and with others
|
|
76
96
|
|
|
77
|
-
**On its own:** it needs an auth collection (default `users`) and your `canMasquerade`. It
|
|
97
|
+
**On its own:** it needs an auth collection (default `users`) with sessions on, which is Payload's default, and your `canMasquerade`. It doesn't need any other plugin. Auditing is up to your `onStart` and `onStop`.
|
|
78
98
|
|
|
79
99
|
**Works with:**
|
|
80
100
|
- **Audit Trail:** call Audit Trail's `recordEvent` from `onStart` and `onStop` (with `masquerade` in its `actions`), and use `masqueraderOf(req)` in its `via` so a change made while masquerading says who really made it.
|
|
@@ -103,7 +123,7 @@ export default buildConfig({
|
|
|
103
123
|
req,
|
|
104
124
|
})
|
|
105
125
|
},
|
|
106
|
-
onStop: async ({ req, masqueraderId, targetId, expired }) => {
|
|
126
|
+
onStop: async ({ req, masqueraderId, targetId, expired, revoked }) => {
|
|
107
127
|
/* … */
|
|
108
128
|
},
|
|
109
129
|
}),
|
|
@@ -135,7 +155,8 @@ import { MasqueradeBanner } from '@extantape/payload-plugin-masq/rsc'
|
|
|
135
155
|
| `adminBanner` | `true` | Banner in the admin header. |
|
|
136
156
|
| `adminView` | `true` | Masquerade area and nav link. |
|
|
137
157
|
| `listColumn` | `true` | Masquerade column in the users list (added to `defaultColumns`). |
|
|
138
|
-
| `
|
|
158
|
+
| `recheck` | | `({ payload, req, masquerader, target }) => boolean`, asked on every request a borrowed session makes, after `canMasquerade`. Only exactly `true` keeps the session; anything else, or a throw, ends it. Use it for checks `canMasquerade` doesn't make, such as a deny list. `req.user` isn't set yet. |
|
|
159
|
+
| `onStart`, `onStop` | | Audit hooks. `onStop` gets `revoked: true` when the per-request check ended the session. |
|
|
139
160
|
| `enabled` | `true` | |
|
|
140
161
|
|
|
141
162
|
## Endpoints
|
package/dist/endpoints.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { addDataAndFileToRequest, APIError, getFieldsToSign, jwtSign } from 'payload';
|
|
2
2
|
import { addSessionToUser, parseCookies } from 'payload/shared';
|
|
3
|
-
import { BORROWED_CLAIM, borrowedClaim, cookie, encodeState, isMasquerading, masqOptions, masqStateOf, RETURN_COOKIE, STATE_COOKIE } from './state.js';
|
|
3
|
+
import { BORROWED_CLAIM, borrowedClaim, cookie, encodeState, isMasquerading, masqOptions, masqStateOf, RETURN_COOKIE, sessionsOn, STATE_COOKIE } from './state.js';
|
|
4
4
|
import { mayMasquerade } from './access.js';
|
|
5
5
|
const STATE_SECONDS = 24 * 60 * 60;
|
|
6
6
|
const json = (body, cookies = [], status = 200) => {
|
|
@@ -24,6 +24,9 @@ export const startEndpoint = {
|
|
|
24
24
|
handler: async (req) => {
|
|
25
25
|
const opts = masqOptions(req.payload);
|
|
26
26
|
const user = signedIn(req);
|
|
27
|
+
// Without sessions a borrowed token can't be ended early, so none is handed out.
|
|
28
|
+
if (!sessionsOn(req.payload, opts.collection))
|
|
29
|
+
throw new APIError('Masquerade needs sessions turned on.', 500, undefined, true);
|
|
27
30
|
if (isMasquerading(req.payload, req.headers))
|
|
28
31
|
throw new APIError('Stop masquerading first.', 400, undefined, true);
|
|
29
32
|
const own = parseCookies(req.headers).get(tokenCookie(req));
|
|
@@ -84,9 +87,10 @@ export const stopEndpoint = {
|
|
|
84
87
|
// cookie is gone, by the borrowed token's own claim.
|
|
85
88
|
const borrowed = req.user;
|
|
86
89
|
// Only a genuine claim, on the token that signs in the very user this request is authenticated as.
|
|
87
|
-
const claim = borrowedClaim(req.payload, req.headers);
|
|
90
|
+
const claim = borrowed ? borrowedClaim(req.payload, req.headers, { userId: String(borrowed.id), sid: borrowed._sid }) : null;
|
|
88
91
|
const claimedBy = claim && borrowed && claim.id === String(borrowed.id) ? claim.by : null;
|
|
89
|
-
|
|
92
|
+
// With the state cookie, only the borrowed session it names: same target and same masquerader.
|
|
93
|
+
const live = Boolean(borrowed?.collection === opts.collection && claimedBy && (!state || (claim.id === state.as && claimedBy === state.by)));
|
|
90
94
|
if (live && borrowed?._sid) {
|
|
91
95
|
const doc = (await req.payload.findByID({ collection: opts.collection, id: borrowed.id, depth: 0, overrideAccess: true, showHiddenFields: true, req }));
|
|
92
96
|
await req.payload.db.updateOne({
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { masqPlugin, READ_ONLY_MESSAGE } from './plugin.js';
|
|
2
2
|
export { assertNotMasquerading, masqStateOf, masqueraderOf, decodeState, STATE_COOKIE } from './state.js';
|
|
3
3
|
export { searchEndpoint, startEndpoint, stopEndpoint } from './endpoints.js';
|
|
4
|
-
export type { MasqPermissionArgs, MasqPluginOptions, MasqStartArgs, MasqState, MasqStopArgs, MasqUser, ResolvedMasqOptions } from './types.js';
|
|
4
|
+
export type { MasqPermissionArgs, MasqPluginOptions, MasqRecheckArgs, MasqStartArgs, MasqState, MasqStopArgs, MasqUser, ResolvedMasqOptions } from './types.js';
|
package/dist/plugin.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { APIError } from 'payload';
|
|
2
2
|
import { searchEndpoint, startEndpoint, stopEndpoint } from './endpoints.js';
|
|
3
|
-
import {
|
|
3
|
+
import { recheckStrategy } from './recheck.js';
|
|
4
|
+
import { borrowedBy, isMasquerading, sessionsOn } from './state.js';
|
|
4
5
|
/** Payload's own bookkeeping, written while simply looking around the admin. */
|
|
6
|
+
const sessionsError = (collection, value) => `payload-plugin-masq: collection "${collection}" has useSessions: ${JSON.stringify(value) ?? 'undefined'}; masq needs useSessions: true to end a borrowed session`;
|
|
5
7
|
const BOOKKEEPING = new Set(['payload-preferences', 'payload-locked-documents']);
|
|
6
8
|
export const READ_ONLY_MESSAGE = 'Masquerade is read-only: nothing can be created, changed or deleted while masquerading.';
|
|
7
9
|
/**
|
|
@@ -68,11 +70,23 @@ export const masqPlugin = (options) => (config) => {
|
|
|
68
70
|
enabled: true,
|
|
69
71
|
onStart: options.onStart,
|
|
70
72
|
onStop: options.onStop,
|
|
73
|
+
recheck: options.recheck,
|
|
71
74
|
apiRoute: config.routes?.api ?? '/api',
|
|
72
75
|
adminRoute,
|
|
73
76
|
};
|
|
74
|
-
|
|
77
|
+
const target = (config.collections ?? []).find((c) => c.slug === collection);
|
|
78
|
+
if (!target)
|
|
75
79
|
throw new Error(`payload-plugin-masq: no collection "${collection}"`);
|
|
80
|
+
if (!target.auth)
|
|
81
|
+
throw new Error(`payload-plugin-masq: collection "${collection}" is not an auth collection`);
|
|
82
|
+
// The recheck and the stop endpoint end a borrowed token by deleting its session. Without sessions there is
|
|
83
|
+
// nothing to delete, and a demoted masquerader would keep the token until it expires.
|
|
84
|
+
// Payload turns sessions off for any falsy value and only fills in its default (true) for null or undefined.
|
|
85
|
+
const useSessions = typeof target.auth === 'object' ? target.auth.useSessions : undefined;
|
|
86
|
+
if (useSessions != null && useSessions !== true)
|
|
87
|
+
throw new Error(sessionsError(collection, useSessions));
|
|
88
|
+
if (options.readOnly !== undefined && typeof options.readOnly !== 'boolean')
|
|
89
|
+
throw new Error('payload-plugin-masq: readOnly must be true or false');
|
|
76
90
|
const components = config.admin?.components ?? {};
|
|
77
91
|
const globals = resolved.readOnly
|
|
78
92
|
? (config.globals ?? []).map((g) => ({
|
|
@@ -91,8 +105,15 @@ export const masqPlugin = (options) => (config) => {
|
|
|
91
105
|
},
|
|
92
106
|
}))
|
|
93
107
|
: config.globals;
|
|
108
|
+
// Another plugin or the host can still turn sessions off after this point, so check the built config too.
|
|
109
|
+
const onInit = config.onInit;
|
|
94
110
|
return {
|
|
95
111
|
...config,
|
|
112
|
+
onInit: async (payload) => {
|
|
113
|
+
if (!sessionsOn(payload, collection))
|
|
114
|
+
throw new Error(sessionsError(collection, payload.collections[collection]?.config.auth?.useSessions));
|
|
115
|
+
await onInit?.(payload);
|
|
116
|
+
},
|
|
96
117
|
globals,
|
|
97
118
|
custom: { ...config.custom, masq: resolved },
|
|
98
119
|
admin: {
|
|
@@ -113,8 +134,11 @@ export const masqPlugin = (options) => (config) => {
|
|
|
113
134
|
if (c.slug !== collection)
|
|
114
135
|
return { ...c, hooks };
|
|
115
136
|
const columns = c.admin?.defaultColumns;
|
|
137
|
+
// Our recheck goes first, so a revoked borrowed session is gone before Payload's JWT strategy reads it.
|
|
138
|
+
const auth = typeof c.auth === 'object' ? { ...c.auth, strategies: [recheckStrategy, ...(c.auth.strategies ?? [])] } : { strategies: [recheckStrategy] };
|
|
116
139
|
return {
|
|
117
140
|
...c,
|
|
141
|
+
auth,
|
|
118
142
|
hooks: { ...hooks, beforeOperation: [...(hooks?.beforeOperation ?? []), noBorrowedRefresh] },
|
|
119
143
|
admin: resolved.listColumn && columns ? { ...c.admin, defaultColumns: [...columns, 'masq'] } : c.admin,
|
|
120
144
|
endpoints: [stopEndpoint, searchEndpoint, startEndpoint, ...(c.endpoints || [])],
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AuthStrategy } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Rechecks every borrowed session on every request. It runs before Payload's own JWT strategy and never signs
|
|
4
|
+
* anyone in itself. When the masquerader may no longer masquerade as the target (canMasquerade, and recheck if
|
|
5
|
+
* set, no longer answer exactly true), or either account is gone, it deletes the borrowed session from the
|
|
6
|
+
* target's sessions, so the JWT strategy that follows refuses the token, from a cookie or a header alike.
|
|
7
|
+
*
|
|
8
|
+
* It fails closed: if the recheck itself fails (a read or the delete throws), the borrowed token is taken out
|
|
9
|
+
* of the headers the later strategies read, so the request runs signed out.
|
|
10
|
+
*/
|
|
11
|
+
export declare const recheckStrategy: AuthStrategy;
|
package/dist/recheck.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { exactlyTrue, mayMasquerade } from './access.js';
|
|
2
|
+
import { borrowedClaims, masqOptions, sessionsOn } from './state.js';
|
|
3
|
+
const load = (payload, collection, id) => payload.findByID({ collection: collection, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true });
|
|
4
|
+
/** The request path without trailing slashes. */
|
|
5
|
+
const pathOf = (url) => new URL(url, 'http://x').pathname.replace(/\/+$/, '');
|
|
6
|
+
/**
|
|
7
|
+
* The same headers without the given borrowed tokens, so the strategies after this one (Payload's JWT strategy
|
|
8
|
+
* among them) find no token to sign in with. The request's own headers are left as they are.
|
|
9
|
+
*/
|
|
10
|
+
function withoutTokens(payload, headers, claims) {
|
|
11
|
+
const out = new Headers(headers);
|
|
12
|
+
const name = `${payload.config?.cookiePrefix ?? 'payload'}-token`;
|
|
13
|
+
for (const c of claims) {
|
|
14
|
+
if (c.from === 'header')
|
|
15
|
+
out.delete('Authorization');
|
|
16
|
+
else {
|
|
17
|
+
const kept = (out.get('Cookie') ?? '')
|
|
18
|
+
.split(';')
|
|
19
|
+
.filter((part) => part.split('=')[0].trim() !== name)
|
|
20
|
+
.join(';');
|
|
21
|
+
if (kept.trim())
|
|
22
|
+
out.set('Cookie', kept);
|
|
23
|
+
else
|
|
24
|
+
out.delete('Cookie');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
const MAX_TRIES = 3;
|
|
30
|
+
/**
|
|
31
|
+
* Removes the borrowed session from the target's sessions, reading the sessions again right before the write so
|
|
32
|
+
* a sign-in that happened meanwhile is kept. In a transaction when the database supports one, so two requests
|
|
33
|
+
* revoking the same session at once conflict and the loser reads again. Answers whether this call removed it,
|
|
34
|
+
* so onStop is reported once. Throws when it can't be sure the session is gone.
|
|
35
|
+
*/
|
|
36
|
+
async function revoke(payload, collection, targetId, sid) {
|
|
37
|
+
let last;
|
|
38
|
+
for (let i = 0; i < MAX_TRIES; i++) {
|
|
39
|
+
const transactionID = (await payload.db.beginTransaction?.()) ?? undefined;
|
|
40
|
+
const req = (transactionID ? { transactionID } : {});
|
|
41
|
+
try {
|
|
42
|
+
const fresh = (await payload.db.findOne({ collection, where: { id: { equals: targetId } }, req }));
|
|
43
|
+
const sessions = fresh?.sessions ?? [];
|
|
44
|
+
const removed = sessions.some((s) => s.id === sid);
|
|
45
|
+
if (removed)
|
|
46
|
+
await payload.db.updateOne({ collection, id: targetId, data: { sessions: sessions.filter((s) => s.id !== sid) }, req, returning: false });
|
|
47
|
+
if (transactionID)
|
|
48
|
+
await payload.db.commitTransaction(transactionID);
|
|
49
|
+
return removed;
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
last = err;
|
|
53
|
+
if (transactionID)
|
|
54
|
+
await payload.db.rollbackTransaction(transactionID).catch(() => undefined);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
throw last;
|
|
58
|
+
}
|
|
59
|
+
async function recheckClaim(payload, opts, req, claim, now) {
|
|
60
|
+
if (!claim.sid || !claim.id || (claim.exp !== null && claim.exp <= now))
|
|
61
|
+
return;
|
|
62
|
+
const target = await load(payload, opts.collection, claim.id);
|
|
63
|
+
if (!target?.sessions?.some((s) => s.id === claim.sid))
|
|
64
|
+
return;
|
|
65
|
+
const masquerader = await load(payload, opts.collection, claim.by);
|
|
66
|
+
const allowed = masquerader !== null &&
|
|
67
|
+
(await mayMasquerade(opts, { payload, user: masquerader, target })) &&
|
|
68
|
+
(!opts.recheck || (await exactlyTrue(() => opts.recheck({ payload, req, masquerader, target }))));
|
|
69
|
+
if (allowed)
|
|
70
|
+
return;
|
|
71
|
+
if (!(await revoke(payload, opts.collection, target.id, claim.sid)))
|
|
72
|
+
return;
|
|
73
|
+
try {
|
|
74
|
+
await opts.onStop?.({ req: req, masqueraderId: claim.by, targetId: String(target.id), expired: false, restored: false, revoked: true });
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
payload.logger.error({ err, msg: 'payload-plugin-masq: onStop failed after a revoked masquerade' });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Rechecks every borrowed session on every request. It runs before Payload's own JWT strategy and never signs
|
|
82
|
+
* anyone in itself. When the masquerader may no longer masquerade as the target (canMasquerade, and recheck if
|
|
83
|
+
* set, no longer answer exactly true), or either account is gone, it deletes the borrowed session from the
|
|
84
|
+
* target's sessions, so the JWT strategy that follows refuses the token, from a cookie or a header alike.
|
|
85
|
+
*
|
|
86
|
+
* It fails closed: if the recheck itself fails (a read or the delete throws), the borrowed token is taken out
|
|
87
|
+
* of the headers the later strategies read, so the request runs signed out.
|
|
88
|
+
*/
|
|
89
|
+
export const recheckStrategy = {
|
|
90
|
+
name: 'masq-recheck',
|
|
91
|
+
authenticate: async (args) => {
|
|
92
|
+
const { headers, payload, req } = args;
|
|
93
|
+
let claims = [];
|
|
94
|
+
try {
|
|
95
|
+
claims = borrowedClaims(payload, headers);
|
|
96
|
+
if (!claims.length)
|
|
97
|
+
return { user: null };
|
|
98
|
+
const opts = masqOptions(payload);
|
|
99
|
+
if (!opts)
|
|
100
|
+
throw new Error('masq options are missing');
|
|
101
|
+
// Without sessions nothing can end a borrowed token, so it never signs in.
|
|
102
|
+
if (!sessionsOn(payload, opts.collection))
|
|
103
|
+
throw new Error('the masquerade collection has sessions turned off');
|
|
104
|
+
// The stop endpoint ends the borrowed session itself and reports it once through onStop.
|
|
105
|
+
if (req?.url && req.method === 'POST' && pathOf(req.url) === `${opts.apiRoute}/${opts.collection}/masq/stop`)
|
|
106
|
+
return { user: null };
|
|
107
|
+
const now = Date.now() / 1000;
|
|
108
|
+
const failed = [];
|
|
109
|
+
// One recheck per borrowed session, even when its token comes in the cookie and the header both.
|
|
110
|
+
const outcome = new Map();
|
|
111
|
+
for (const claim of claims) {
|
|
112
|
+
const key = JSON.stringify([claim.by, claim.id, claim.sid, claim.exp]);
|
|
113
|
+
if (!outcome.has(key)) {
|
|
114
|
+
try {
|
|
115
|
+
await recheckClaim(payload, opts, req, claim, now);
|
|
116
|
+
outcome.set(key, true);
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
payload.logger.error({ err, msg: 'payload-plugin-masq: could not recheck a borrowed session; this request runs signed out' });
|
|
120
|
+
outcome.set(key, false);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!outcome.get(key))
|
|
124
|
+
failed.push(claim);
|
|
125
|
+
}
|
|
126
|
+
if (failed.length)
|
|
127
|
+
args.headers = withoutTokens(payload, headers, failed);
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
payload.logger.error({ err, msg: 'payload-plugin-masq: could not recheck a borrowed session; this request runs signed out' });
|
|
131
|
+
if (claims.length)
|
|
132
|
+
args.headers = withoutTokens(payload, headers, claims);
|
|
133
|
+
}
|
|
134
|
+
return { user: null };
|
|
135
|
+
},
|
|
136
|
+
};
|
package/dist/state.d.ts
CHANGED
|
@@ -15,10 +15,37 @@ export declare const BORROWED_CLAIM = "masqBy";
|
|
|
15
15
|
* (`id`). Only a token signed with Payload's secret counts, checked the way Payload checks
|
|
16
16
|
* its own JWTs (HS256), so a forged claim is ignored.
|
|
17
17
|
*/
|
|
18
|
-
export
|
|
18
|
+
export type BorrowedClaim = {
|
|
19
|
+
by: string;
|
|
20
|
+
id: string;
|
|
21
|
+
sid: string | null;
|
|
22
|
+
exp: number | null;
|
|
23
|
+
token: string;
|
|
24
|
+
from: 'cookie' | 'header';
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Every genuine borrowed claim in the request, cookie first, then the Authorization header. It reads tokens at
|
|
28
|
+
* least as loosely as Payload's JWT strategy and jose do (padding or whitespace in the signature, spaces around
|
|
29
|
+
* the cookie name, any letter case in the scheme), so no spelling Payload signs in with escapes the checks.
|
|
30
|
+
*/
|
|
31
|
+
export declare function borrowedClaims(payload: Payload, headers: Headers | null | undefined): BorrowedClaim[];
|
|
32
|
+
/**
|
|
33
|
+
* The first borrowed claim, or with `session`, the claim on the very token that signed in: the same user and the
|
|
34
|
+
* same session id. A second token for the same user (another masquerader's, or the user's own) is never picked.
|
|
35
|
+
*/
|
|
36
|
+
export declare function borrowedClaim(payload: Payload, headers: Headers | null | undefined, session?: {
|
|
37
|
+
userId: string;
|
|
38
|
+
sid: string | undefined;
|
|
39
|
+
}): {
|
|
19
40
|
by: string;
|
|
20
41
|
id: string;
|
|
21
42
|
} | null;
|
|
43
|
+
/**
|
|
44
|
+
* Whether the masquerade collection, as Payload finally built it, keeps sessions. Payload turns sessions off for
|
|
45
|
+
* any falsy useSessions, and another plugin or the host can change it after masq has run, so this reads the
|
|
46
|
+
* built config and only exactly true counts.
|
|
47
|
+
*/
|
|
48
|
+
export declare const sessionsOn: (payload: Payload, collection: string) => boolean;
|
|
22
49
|
/** The masquerader's id if the request carries a genuine borrowed session's token. */
|
|
23
50
|
export declare const borrowedBy: (payload: Payload, headers: Headers | null | undefined) => string | null;
|
|
24
51
|
/**
|
package/dist/state.js
CHANGED
|
@@ -31,38 +31,95 @@ export const masqStateOf = (payload, headers) => headers ? decodeState(payload.s
|
|
|
31
31
|
/** Claim that marks a borrowed session's token, with the masquerader's id. */
|
|
32
32
|
export const BORROWED_CLAIM = 'masqBy';
|
|
33
33
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
* (`id`). Only a token signed with Payload's secret counts, checked the way Payload checks
|
|
37
|
-
* its own JWTs (HS256), so a forged claim is ignored.
|
|
34
|
+
* Every value the request carries for the cookie `name`, read at least as loosely as Payload's own JWT strategy
|
|
35
|
+
* reads it: names trimmed, every occurrence kept (Payload keeps the last), each value both as sent and URI-decoded.
|
|
38
36
|
*/
|
|
39
|
-
|
|
37
|
+
function cookieValues(headers, name) {
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const part of (headers.get('Cookie') ?? '').split(';')) {
|
|
40
|
+
const [key, ...rest] = part.split('=');
|
|
41
|
+
if (key?.trim() !== name)
|
|
42
|
+
continue;
|
|
43
|
+
const raw = rest.join('=');
|
|
44
|
+
out.push(raw);
|
|
45
|
+
try {
|
|
46
|
+
const decoded = decodeURI(raw);
|
|
47
|
+
if (decoded !== raw)
|
|
48
|
+
out.push(decoded);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// Payload skips a value it can't decode; the raw value is still checked.
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
/** Base64url decoded the way jose decodes it (Node's decoder, which skips whitespace, padding and other stray characters). */
|
|
57
|
+
const b64 = (s) => Buffer.from(s, 'base64url');
|
|
58
|
+
/**
|
|
59
|
+
* Every genuine borrowed claim in the request, cookie first, then the Authorization header. It reads tokens at
|
|
60
|
+
* least as loosely as Payload's JWT strategy and jose do (padding or whitespace in the signature, spaces around
|
|
61
|
+
* the cookie name, any letter case in the scheme), so no spelling Payload signs in with escapes the checks.
|
|
62
|
+
*/
|
|
63
|
+
export function borrowedClaims(payload, headers) {
|
|
40
64
|
if (!headers || !payload.secret)
|
|
41
|
-
return
|
|
65
|
+
return [];
|
|
42
66
|
const auth = headers.get('Authorization') ?? '';
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
67
|
+
const scheme = /^\s*(?:jwt|bearer)\s+/i.exec(auth);
|
|
68
|
+
const tokens = [
|
|
69
|
+
...cookieValues(headers, `${payload.config?.cookiePrefix ?? 'payload'}-token`).map((t) => [t, 'cookie']),
|
|
70
|
+
...(scheme ? [[auth.slice(scheme[0].length), 'header']] : []),
|
|
71
|
+
];
|
|
72
|
+
const out = [];
|
|
73
|
+
const seen = new Set();
|
|
74
|
+
for (const [token, from] of tokens) {
|
|
75
|
+
const [head, body, sig] = token.split('.');
|
|
46
76
|
if (!head || !body || !sig)
|
|
47
77
|
continue;
|
|
48
|
-
|
|
49
|
-
const
|
|
78
|
+
// The same signed token repeated (or its raw and decoded copies) counts once.
|
|
79
|
+
const key = `${from} ${head}.${body}`;
|
|
80
|
+
if (seen.has(key))
|
|
81
|
+
continue;
|
|
82
|
+
const expected = crypto.createHmac('sha256', payload.secret).update(`${head}.${body}`).digest();
|
|
83
|
+
const given = b64(sig);
|
|
50
84
|
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given))
|
|
51
85
|
continue;
|
|
86
|
+
seen.add(key);
|
|
52
87
|
try {
|
|
53
|
-
if (JSON.parse(
|
|
88
|
+
if (JSON.parse(b64(head).toString('utf8')).alg !== 'HS256')
|
|
54
89
|
continue;
|
|
55
|
-
const claims = JSON.parse(
|
|
90
|
+
const claims = JSON.parse(b64(body).toString('utf8'));
|
|
56
91
|
const by = claims[BORROWED_CLAIM];
|
|
57
92
|
if (typeof by === 'string' && by)
|
|
58
|
-
|
|
93
|
+
out.push({
|
|
94
|
+
by,
|
|
95
|
+
id: String(claims.id ?? ''),
|
|
96
|
+
sid: typeof claims.sid === 'string' ? claims.sid : null,
|
|
97
|
+
exp: typeof claims.exp === 'number' ? claims.exp : null,
|
|
98
|
+
token,
|
|
99
|
+
from,
|
|
100
|
+
});
|
|
59
101
|
}
|
|
60
102
|
catch {
|
|
61
103
|
// Not a JWT we can read: not a borrowed session.
|
|
62
104
|
}
|
|
63
105
|
}
|
|
64
|
-
return
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The first borrowed claim, or with `session`, the claim on the very token that signed in: the same user and the
|
|
110
|
+
* same session id. A second token for the same user (another masquerader's, or the user's own) is never picked.
|
|
111
|
+
*/
|
|
112
|
+
export function borrowedClaim(payload, headers, session) {
|
|
113
|
+
const all = borrowedClaims(payload, headers);
|
|
114
|
+
const c = session === undefined ? all[0] : session.sid ? all.find((x) => x.id === session.userId && x.sid === session.sid) : undefined;
|
|
115
|
+
return c ? { by: c.by, id: c.id } : null;
|
|
65
116
|
}
|
|
117
|
+
/**
|
|
118
|
+
* Whether the masquerade collection, as Payload finally built it, keeps sessions. Payload turns sessions off for
|
|
119
|
+
* any falsy useSessions, and another plugin or the host can change it after masq has run, so this reads the
|
|
120
|
+
* built config and only exactly true counts.
|
|
121
|
+
*/
|
|
122
|
+
export const sessionsOn = (payload, collection) => payload.collections?.[collection]?.config?.auth?.useSessions === true;
|
|
66
123
|
/** The masquerader's id if the request carries a genuine borrowed session's token. */
|
|
67
124
|
export const borrowedBy = (payload, headers) => borrowedClaim(payload, headers)?.by ?? null;
|
|
68
125
|
/**
|
package/dist/types.d.ts
CHANGED
|
@@ -25,6 +25,17 @@ export type MasqStopArgs = {
|
|
|
25
25
|
expired: boolean;
|
|
26
26
|
/** The masquerader's own session was restored. */
|
|
27
27
|
restored: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* The plugin ended the borrowed session itself, because a recheck said no: `canMasquerade`
|
|
30
|
+
* (or `recheck`) no longer answered exactly `true`, or either account is gone.
|
|
31
|
+
*/
|
|
32
|
+
revoked?: boolean;
|
|
33
|
+
};
|
|
34
|
+
export type MasqRecheckArgs = {
|
|
35
|
+
payload: Payload;
|
|
36
|
+
req?: PayloadRequest;
|
|
37
|
+
masquerader: MasqUser;
|
|
38
|
+
target: MasqUser;
|
|
28
39
|
};
|
|
29
40
|
export type MasqPluginOptions = {
|
|
30
41
|
/** Auth collection to masquerade in. Default `users`. */
|
|
@@ -58,11 +69,18 @@ export type MasqPluginOptions = {
|
|
|
58
69
|
listColumn?: boolean;
|
|
59
70
|
/** Add the "Masquerade" view (admin-only user search) and its nav link. Default true. */
|
|
60
71
|
adminView?: boolean;
|
|
72
|
+
/**
|
|
73
|
+
* An extra check run with `canMasquerade` on every request a borrowed session makes. Only an
|
|
74
|
+
* answer of exactly `true` keeps the session; anything else, a thrown error included, ends it.
|
|
75
|
+
* Use it for rules that don't belong in `canMasquerade`, such as a deny list. Keep it cheap:
|
|
76
|
+
* it runs once per request while masquerading.
|
|
77
|
+
*/
|
|
78
|
+
recheck?: (args: MasqRecheckArgs) => unknown;
|
|
61
79
|
onStart?: (args: MasqStartArgs) => void | Promise<void>;
|
|
62
80
|
onStop?: (args: MasqStopArgs) => void | Promise<void>;
|
|
63
81
|
enabled?: boolean;
|
|
64
82
|
};
|
|
65
|
-
export type ResolvedMasqOptions = Required<Omit<MasqPluginOptions, 'onStart' | 'onStop' | 'startPath'>> & Pick<MasqPluginOptions, 'onStart' | 'onStop'> & {
|
|
83
|
+
export type ResolvedMasqOptions = Required<Omit<MasqPluginOptions, 'onStart' | 'onStop' | 'startPath' | 'recheck'>> & Pick<MasqPluginOptions, 'onStart' | 'onStop' | 'recheck'> & {
|
|
66
84
|
startPath: string;
|
|
67
85
|
apiRoute: string;
|
|
68
86
|
adminRoute: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-masq",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Masquerade for Payload: admins sign in as another user, read-only, to see what they see, with a banner, a one-hour session, an admin-only user search and audit hooks.",
|
|
5
5
|
"homepage": "https://github.com/ExtantApe/payload-plugin-masq#readme",
|
|
6
6
|
"bugs": {
|