@extantape/payload-plugin-masq 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +176 -2
- package/dist/access.d.ts +5 -0
- package/dist/access.js +11 -0
- package/dist/client/MasqueradeButton.d.ts +12 -0
- package/dist/client/MasqueradeButton.js +30 -0
- package/dist/client/MasqueradeSearch.d.ts +13 -0
- package/dist/client/MasqueradeSearch.js +90 -0
- package/dist/client/ReturnButton.d.ts +7 -0
- package/dist/client/ReturnButton.js +13 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +3 -0
- package/dist/endpoints.d.ts +12 -0
- package/dist/endpoints.js +159 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/plugin.d.ts +20 -0
- package/dist/plugin.js +160 -0
- package/dist/recheck.d.ts +11 -0
- package/dist/recheck.js +136 -0
- package/dist/rsc/MasqueradeBanner.d.ts +18 -0
- package/dist/rsc/MasqueradeBanner.js +56 -0
- package/dist/rsc/MasqueradeField.d.ts +14 -0
- package/dist/rsc/MasqueradeField.js +27 -0
- package/dist/rsc/MasqueradeView.d.ts +9 -0
- package/dist/rsc/MasqueradeView.js +24 -0
- package/dist/rsc/currentUser.d.ts +4 -0
- package/dist/rsc/currentUser.js +7 -0
- package/dist/rsc/index.d.ts +3 -0
- package/dist/rsc/index.js +3 -0
- package/dist/state.d.ts +64 -0
- package/dist/state.js +154 -0
- package/dist/types.d.ts +98 -0
- package/dist/types.js +1 -0
- package/package.json +79 -4
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { searchEndpoint, startEndpoint, stopEndpoint } from './endpoints.js';
|
|
3
|
+
import { recheckStrategy } from './recheck.js';
|
|
4
|
+
import { borrowedBy, isMasquerading, sessionsOn } from './state.js';
|
|
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`;
|
|
7
|
+
const BOOKKEEPING = new Set(['payload-preferences', 'payload-locked-documents']);
|
|
8
|
+
export const READ_ONLY_MESSAGE = 'Masquerade is read-only: nothing can be created, changed or deleted while masquerading.';
|
|
9
|
+
/**
|
|
10
|
+
* Every collection operation in Payload 3.92 that writes and runs `beforeOperation`. Login
|
|
11
|
+
* (it only records the sign-in) and refresh (refused separately) are left out.
|
|
12
|
+
*/
|
|
13
|
+
const COLLECTION_WRITES = new Set(['create', 'update', 'delete', 'restoreVersion', 'unlock', 'forgotPassword', 'resetPassword']);
|
|
14
|
+
/** Global operations that write. A global restore skips `beforeChange`, so the guard sits here. */
|
|
15
|
+
const GLOBAL_WRITES = new Set(['update', 'restoreVersion']);
|
|
16
|
+
/** Read-only masquerade: refuse writes while masquerading (the plugin's own writes are marked internal). */
|
|
17
|
+
const readOnlyGuard = ({ args, operation, req }) => {
|
|
18
|
+
if (req.context?.masqInternal)
|
|
19
|
+
return args;
|
|
20
|
+
if (COLLECTION_WRITES.has(operation) && isMasquerading(req.payload, req.headers))
|
|
21
|
+
throw new APIError(READ_ONLY_MESSAGE, 403, undefined, true);
|
|
22
|
+
return args;
|
|
23
|
+
};
|
|
24
|
+
const globalReadOnlyGuard = ({ args, operation, req }) => {
|
|
25
|
+
if (req.context?.masqInternal)
|
|
26
|
+
return args;
|
|
27
|
+
if (GLOBAL_WRITES.has(operation) && isMasquerading(req.payload, req.headers))
|
|
28
|
+
throw new APIError(READ_ONLY_MESSAGE, 403, undefined, true);
|
|
29
|
+
return args;
|
|
30
|
+
};
|
|
31
|
+
/** A borrowed session ends on time: it can't be refreshed (the admin refreshes tokens while you're active). */
|
|
32
|
+
const noBorrowedRefresh = ({ args, operation, req }) => {
|
|
33
|
+
if (operation === 'refresh' && borrowedBy(req.payload, req.headers))
|
|
34
|
+
throw new APIError('A masquerade session can’t be extended.', 403, undefined, true);
|
|
35
|
+
return args;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Masquerade: an admin signs in as another user to see what they see.
|
|
39
|
+
*
|
|
40
|
+
* - The masquerader gets a real, short Payload session of the target (the same
|
|
41
|
+
* session machinery as a normal login), so every access rule applies exactly
|
|
42
|
+
* as for that user. Default one hour.
|
|
43
|
+
* - Their own token waits in an httpOnly cookie sent only to the stop
|
|
44
|
+
* endpoint, and comes back only if it is still valid and they may still
|
|
45
|
+
* masquerade. The borrowed session is ended on return.
|
|
46
|
+
* - A signed cookie records who is masquerading as whom, for the banner and
|
|
47
|
+
* for audit trails (`masqueraderOf(req)`).
|
|
48
|
+
* - The admin gets a "Masquerade as this user" button on each user, a
|
|
49
|
+
* Masquerade view with a user search (only for people allowed to
|
|
50
|
+
* masquerade, reading with their own access), and a banner with
|
|
51
|
+
* "Return to my account". Put `<MasqueradeBanner />` in your site layout too.
|
|
52
|
+
*/
|
|
53
|
+
export const masqPlugin = (options) => (config) => {
|
|
54
|
+
if (options.enabled === false)
|
|
55
|
+
return config;
|
|
56
|
+
const collection = options.collection ?? 'users';
|
|
57
|
+
const adminRoute = config.routes?.admin ?? '/admin';
|
|
58
|
+
const resolved = {
|
|
59
|
+
collection,
|
|
60
|
+
canMasquerade: options.canMasquerade,
|
|
61
|
+
duration: options.duration ?? 3600,
|
|
62
|
+
readOnly: options.readOnly ?? true,
|
|
63
|
+
requireReason: options.requireReason ?? false,
|
|
64
|
+
labelField: options.labelField ?? 'email',
|
|
65
|
+
searchFields: options.searchFields ?? ['email'],
|
|
66
|
+
startPath: options.startPath ?? adminRoute,
|
|
67
|
+
adminBanner: options.adminBanner ?? true,
|
|
68
|
+
adminView: options.adminView ?? true,
|
|
69
|
+
listColumn: options.listColumn ?? true,
|
|
70
|
+
enabled: true,
|
|
71
|
+
onStart: options.onStart,
|
|
72
|
+
onStop: options.onStop,
|
|
73
|
+
recheck: options.recheck,
|
|
74
|
+
apiRoute: config.routes?.api ?? '/api',
|
|
75
|
+
adminRoute,
|
|
76
|
+
};
|
|
77
|
+
const target = (config.collections ?? []).find((c) => c.slug === collection);
|
|
78
|
+
if (!target)
|
|
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');
|
|
90
|
+
const components = config.admin?.components ?? {};
|
|
91
|
+
const globals = resolved.readOnly
|
|
92
|
+
? (config.globals ?? []).map((g) => ({
|
|
93
|
+
...g,
|
|
94
|
+
hooks: {
|
|
95
|
+
...g.hooks,
|
|
96
|
+
beforeOperation: [...(g.hooks?.beforeOperation ?? []), globalReadOnlyGuard],
|
|
97
|
+
beforeChange: [
|
|
98
|
+
...(g.hooks?.beforeChange ?? []),
|
|
99
|
+
(({ data, req }) => {
|
|
100
|
+
if (!req.context?.masqInternal && isMasquerading(req.payload, req.headers))
|
|
101
|
+
throw new APIError(READ_ONLY_MESSAGE, 403, undefined, true);
|
|
102
|
+
return data;
|
|
103
|
+
}),
|
|
104
|
+
],
|
|
105
|
+
},
|
|
106
|
+
}))
|
|
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;
|
|
110
|
+
return {
|
|
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
|
+
},
|
|
117
|
+
globals,
|
|
118
|
+
custom: { ...config.custom, masq: resolved },
|
|
119
|
+
admin: {
|
|
120
|
+
...config.admin,
|
|
121
|
+
components: {
|
|
122
|
+
...components,
|
|
123
|
+
header: [...(components.header ?? []), ...(resolved.adminBanner ? ['@extantape/payload-plugin-masq/rsc#AdminMasqueradeBanner'] : [])],
|
|
124
|
+
afterNavLinks: [...(components.afterNavLinks ?? []), ...(resolved.adminView ? ['@extantape/payload-plugin-masq/rsc#MasqueradeNavLink'] : [])],
|
|
125
|
+
views: {
|
|
126
|
+
...components.views,
|
|
127
|
+
...(resolved.adminView ? { masquerade: { Component: '@extantape/payload-plugin-masq/rsc#MasqueradeView', path: '/masquerade' } } : {}),
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
collections: (config.collections ?? []).map((c) => {
|
|
132
|
+
const guarded = resolved.readOnly && !BOOKKEEPING.has(c.slug);
|
|
133
|
+
const hooks = guarded ? { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), readOnlyGuard] } : c.hooks;
|
|
134
|
+
if (c.slug !== collection)
|
|
135
|
+
return { ...c, hooks };
|
|
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] };
|
|
139
|
+
return {
|
|
140
|
+
...c,
|
|
141
|
+
auth,
|
|
142
|
+
hooks: { ...hooks, beforeOperation: [...(hooks?.beforeOperation ?? []), noBorrowedRefresh] },
|
|
143
|
+
admin: resolved.listColumn && columns ? { ...c.admin, defaultColumns: [...columns, 'masq'] } : c.admin,
|
|
144
|
+
endpoints: [stopEndpoint, searchEndpoint, startEndpoint, ...(c.endpoints || [])],
|
|
145
|
+
fields: [
|
|
146
|
+
{
|
|
147
|
+
name: 'masq',
|
|
148
|
+
type: 'ui',
|
|
149
|
+
label: 'Masquerade',
|
|
150
|
+
admin: {
|
|
151
|
+
position: 'sidebar',
|
|
152
|
+
components: { Field: '@extantape/payload-plugin-masq/rsc#MasqueradeField', Cell: '@extantape/payload-plugin-masq/rsc#MasqueradeCell' },
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
...c.fields,
|
|
156
|
+
],
|
|
157
|
+
};
|
|
158
|
+
}),
|
|
159
|
+
};
|
|
160
|
+
};
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
/**
|
|
4
|
+
* "You're masquerading as …" with a button back to your own account. Renders
|
|
5
|
+
* nothing unless the request carries a valid masquerade. It names the target only
|
|
6
|
+
* while the borrowed session is live and the masquerader may still masquerade as
|
|
7
|
+
* them; otherwise it says the masquerade is over, names nobody, and offers the way
|
|
8
|
+
* back. Added to the admin header by the plugin; put it in your site layout too:
|
|
9
|
+
* `<MasqueradeBanner payload={payload} />`.
|
|
10
|
+
*/
|
|
11
|
+
export declare function MasqueradeBanner({ payload, className }: {
|
|
12
|
+
payload: Payload;
|
|
13
|
+
className?: string;
|
|
14
|
+
}): Promise<React.JSX.Element | null>;
|
|
15
|
+
/** Admin header slot (registered by the plugin). */
|
|
16
|
+
export declare function AdminMasqueradeBanner({ payload }: {
|
|
17
|
+
payload: Payload;
|
|
18
|
+
}): Promise<React.JSX.Element>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { headers } from 'next/headers.js';
|
|
3
|
+
import { mayMasquerade } from '../access.js';
|
|
4
|
+
import { ReturnButton } from '../client/ReturnButton.js';
|
|
5
|
+
import { masqOptions, masqStateOf } from '../state.js';
|
|
6
|
+
import { currentUser } from './currentUser.js';
|
|
7
|
+
/**
|
|
8
|
+
* "You're masquerading as …" with a button back to your own account. Renders
|
|
9
|
+
* nothing unless the request carries a valid masquerade. It names the target only
|
|
10
|
+
* while the borrowed session is live and the masquerader may still masquerade as
|
|
11
|
+
* them; otherwise it says the masquerade is over, names nobody, and offers the way
|
|
12
|
+
* back. Added to the admin header by the plugin; put it in your site layout too:
|
|
13
|
+
* `<MasqueradeBanner payload={payload} />`.
|
|
14
|
+
*/
|
|
15
|
+
export async function MasqueradeBanner({ payload, className }) {
|
|
16
|
+
const state = masqStateOf(payload, await headers());
|
|
17
|
+
if (!state)
|
|
18
|
+
return null;
|
|
19
|
+
const opts = masqOptions(payload);
|
|
20
|
+
const stopPath = `${opts.apiRoute}/${opts.collection}/masq/stop`;
|
|
21
|
+
const viewer = (await currentUser(payload));
|
|
22
|
+
const live = Boolean(viewer && viewer.collection === opts.collection && String(viewer.id) === state.as);
|
|
23
|
+
const masquerader = live
|
|
24
|
+
? (await payload.findByID({ collection: opts.collection, id: state.by, depth: 0, overrideAccess: true, disableErrors: true }))
|
|
25
|
+
: null;
|
|
26
|
+
const allowed = Boolean(live && masquerader && (await mayMasquerade(opts, { payload, user: masquerader, target: viewer })));
|
|
27
|
+
if (!allowed)
|
|
28
|
+
return (_jsx(Bar, { className: className, stopPath: stopPath, children: live ? 'You may no longer masquerade as this user.' : 'Your masquerade has ended.' }));
|
|
29
|
+
const target = viewer;
|
|
30
|
+
const name = String(target[opts.labelField] ?? target.email ?? state.as);
|
|
31
|
+
const email = target.email && target.email !== name ? ` (${String(target.email)})` : '';
|
|
32
|
+
const minutes = Math.max(0, Math.round((Date.parse(state.until) - Date.now()) / 60000));
|
|
33
|
+
return (_jsxs(Bar, { className: className, stopPath: stopPath, children: ["You\u2019re masquerading as ", _jsx("strong", { children: name }), email, opts.readOnly ? ', read-only' : '', ". ", minutes > 0 ? `Ends in ${minutes} min.` : 'The session has ended.'] }));
|
|
34
|
+
}
|
|
35
|
+
function Bar({ className, stopPath, children }) {
|
|
36
|
+
return (_jsxs("div", { role: "status", className: className ?? 'masq-banner', style: {
|
|
37
|
+
position: 'fixed',
|
|
38
|
+
insetInline: 0,
|
|
39
|
+
bottom: 0,
|
|
40
|
+
zIndex: 1000,
|
|
41
|
+
display: 'flex',
|
|
42
|
+
flexWrap: 'wrap',
|
|
43
|
+
gap: '0.75rem',
|
|
44
|
+
alignItems: 'center',
|
|
45
|
+
justifyContent: 'center',
|
|
46
|
+
padding: '0.6rem 1rem',
|
|
47
|
+
background: '#7c2d12',
|
|
48
|
+
color: '#fff',
|
|
49
|
+
fontSize: '0.9rem',
|
|
50
|
+
boxShadow: '0 -2px 8px rgba(0,0,0,0.25)',
|
|
51
|
+
}, children: [_jsx("span", { children: children }), _jsx(ReturnButton, { stopPath: stopPath })] }));
|
|
52
|
+
}
|
|
53
|
+
/** Admin header slot (registered by the plugin). */
|
|
54
|
+
export async function AdminMasqueradeBanner({ payload }) {
|
|
55
|
+
return _jsx(MasqueradeBanner, { payload: payload });
|
|
56
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest } from 'payload';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
/** Sidebar button on a user's account page, shown only to people allowed to masquerade as that user. */
|
|
4
|
+
export declare function MasqueradeField({ payload, req, id, data }: {
|
|
5
|
+
payload: Payload;
|
|
6
|
+
req: PayloadRequest;
|
|
7
|
+
id?: number | string;
|
|
8
|
+
data?: Record<string, unknown>;
|
|
9
|
+
}): Promise<React.JSX.Element | null>;
|
|
10
|
+
/** Users list column: a Masquerade button per row the viewer may masquerade as. */
|
|
11
|
+
export declare function MasqueradeCell({ payload, rowData }: {
|
|
12
|
+
payload: Payload;
|
|
13
|
+
rowData: Record<string, unknown>;
|
|
14
|
+
}): Promise<React.JSX.Element | null>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { headers } from 'next/headers.js';
|
|
3
|
+
import { mayMasquerade } from '../access.js';
|
|
4
|
+
import { MasqueradeButton } from '../client/MasqueradeButton.js';
|
|
5
|
+
import { isMasquerading, masqOptions } from '../state.js';
|
|
6
|
+
import { currentUser } from './currentUser.js';
|
|
7
|
+
/** Sidebar button on a user's account page, shown only to people allowed to masquerade as that user. */
|
|
8
|
+
export async function MasqueradeField({ payload, req, id, data }) {
|
|
9
|
+
const user = req?.user;
|
|
10
|
+
if (!id || !user || String(user.id) === String(id) || isMasquerading(payload, req.headers))
|
|
11
|
+
return null;
|
|
12
|
+
const opts = masqOptions(payload);
|
|
13
|
+
if (!(await mayMasquerade(opts, { payload, user, target: { ...(data ?? {}), id } })))
|
|
14
|
+
return null;
|
|
15
|
+
return (_jsx(MasqueradeButton, { apiPath: `${opts.apiRoute}/${opts.collection}`, userId: String(id), requireReason: opts.requireReason, hint: `See the site and admin as they do, for ${Math.round(opts.duration / 60)} minutes${opts.readOnly ? ', read-only' : ''}. A banner takes you back.` }));
|
|
16
|
+
}
|
|
17
|
+
/** Users list column: a Masquerade button per row the viewer may masquerade as. */
|
|
18
|
+
export async function MasqueradeCell({ payload, rowData }) {
|
|
19
|
+
const user = await currentUser(payload);
|
|
20
|
+
const id = rowData?.id;
|
|
21
|
+
if (!id || !user || String(user.id) === String(id) || isMasquerading(payload, await headers()))
|
|
22
|
+
return null;
|
|
23
|
+
const opts = masqOptions(payload);
|
|
24
|
+
if (!(await mayMasquerade(opts, { payload, user, target: rowData })))
|
|
25
|
+
return null;
|
|
26
|
+
return _jsx(MasqueradeButton, { apiPath: `${opts.apiRoute}/${opts.collection}`, userId: String(id), requireReason: opts.requireReason, label: "Masquerade" });
|
|
27
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AdminViewServerProps } from 'payload';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
/** The Masquerade area (/admin/masquerade): quick "Masquerade as…" and a user search, for people allowed to masquerade. */
|
|
4
|
+
export declare function MasqueradeView({ initPageResult, params, searchParams }: AdminViewServerProps): Promise<React.JSX.Element>;
|
|
5
|
+
/** Nav link to the Masquerade area, only for people allowed to masquerade. */
|
|
6
|
+
export declare function MasqueradeNavLink({ payload, user }: {
|
|
7
|
+
payload: import('payload').Payload;
|
|
8
|
+
user?: unknown;
|
|
9
|
+
}): Promise<React.JSX.Element | null>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { DefaultTemplate } from '@payloadcms/next/templates';
|
|
3
|
+
import { headers } from 'next/headers.js';
|
|
4
|
+
import { mayMasquerade } from '../access.js';
|
|
5
|
+
import { MasqueradeSearch, QuickMasquerade } from '../client/MasqueradeSearch.js';
|
|
6
|
+
import { isMasquerading, masqOptions } from '../state.js';
|
|
7
|
+
/** The Masquerade area (/admin/masquerade): quick "Masquerade as…" and a user search, for people allowed to masquerade. */
|
|
8
|
+
export async function MasqueradeView({ initPageResult, params, searchParams }) {
|
|
9
|
+
const { req, permissions, visibleEntities, locale } = initPageResult;
|
|
10
|
+
const { payload } = req;
|
|
11
|
+
const opts = masqOptions(payload);
|
|
12
|
+
const user = req.user;
|
|
13
|
+
// Not while masquerading: there is no nesting.
|
|
14
|
+
const nested = isMasquerading(payload, req.headers);
|
|
15
|
+
const allowed = Boolean(user && !nested && (await mayMasquerade(opts, { payload, user })));
|
|
16
|
+
return (_jsx(DefaultTemplate, { i18n: req.i18n, locale: locale, params: params, payload: payload, permissions: permissions, req: req, searchParams: searchParams, user: req.user ?? undefined, visibleEntities: visibleEntities, children: _jsxs("div", { className: "gutter--left gutter--right", style: { paddingBlock: 'calc(var(--base) * 2)' }, children: [_jsx("h1", { children: "Masquerade" }), allowed ? (_jsxs(_Fragment, { children: [_jsxs("p", { style: { maxWidth: 680, marginBottom: 'calc(var(--base) * 1.5)' }, children: ["Sign in as someone to see the site and admin exactly as they do, for ", Math.round(opts.duration / 60), " minutes", opts.readOnly ? ', read-only: you can look everywhere they can, but not create, change or delete anything' : '', ". Find them below, or open their account and use \u201CMasquerade as this user\u201D. A banner takes you back to your own account."] }), _jsx(QuickMasquerade, { apiPath: `${opts.apiRoute}/${opts.collection}`, requireReason: opts.requireReason }), _jsx("h2", { style: { marginTop: 'calc(var(--base) * 2)' }, children: "Find a user" }), _jsx(MasqueradeSearch, { apiPath: `${opts.apiRoute}/${opts.collection}`, adminRoute: opts.adminRoute, collection: opts.collection, requireReason: opts.requireReason })] })) : (_jsx("p", { children: nested ? 'Return to your own account before you masquerade as someone else.' : 'You don’t have permission to masquerade.' }))] }) }));
|
|
17
|
+
}
|
|
18
|
+
/** Nav link to the Masquerade area, only for people allowed to masquerade. */
|
|
19
|
+
export async function MasqueradeNavLink({ payload, user }) {
|
|
20
|
+
const opts = masqOptions(payload);
|
|
21
|
+
if (!user || isMasquerading(payload, await headers()) || !(await mayMasquerade(opts, { payload, user: user })))
|
|
22
|
+
return null;
|
|
23
|
+
return (_jsx("a", { className: "nav__link", href: `${opts.adminRoute}/masquerade`, style: { display: 'block', marginTop: 'calc(var(--base) / 2)' }, children: _jsx("span", { className: "nav__link-label", children: "Masquerade" }) }));
|
|
24
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { headers } from 'next/headers.js';
|
|
2
|
+
import { cache } from 'react';
|
|
3
|
+
/** The signed-in user of this request, looked up once per render. */
|
|
4
|
+
export const currentUser = cache(async (payload) => {
|
|
5
|
+
const { user } = await payload.auth({ headers: await headers() });
|
|
6
|
+
return user ?? null;
|
|
7
|
+
});
|
package/dist/state.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest } from 'payload';
|
|
2
|
+
import type { MasqState, ResolvedMasqOptions } from './types.js';
|
|
3
|
+
export declare const STATE_COOKIE = "payload-masq";
|
|
4
|
+
export declare const RETURN_COOKIE = "payload-masq-return";
|
|
5
|
+
export declare function encodeState(secret: string, state: MasqState): string;
|
|
6
|
+
/** The state from a signed cookie value, or null if missing, forged or malformed. */
|
|
7
|
+
export declare function decodeState(secret: string, raw: string | null | undefined): MasqState | null;
|
|
8
|
+
/** The active masquerade of a request (from its cookies), if any. */
|
|
9
|
+
export declare const masqStateOf: (payload: Payload, headers: Headers | null | undefined) => MasqState | null;
|
|
10
|
+
/** Claim that marks a borrowed session's token, with the masquerader's id. */
|
|
11
|
+
export declare const BORROWED_CLAIM = "masqBy";
|
|
12
|
+
/**
|
|
13
|
+
* The claim of a borrowed masquerade session in the request's Payload token (cookie or
|
|
14
|
+
* Authorization header): the masquerader (`by`) and the account the token signs in as
|
|
15
|
+
* (`id`). Only a token signed with Payload's secret counts, checked the way Payload checks
|
|
16
|
+
* its own JWTs (HS256), so a forged claim is ignored.
|
|
17
|
+
*/
|
|
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
|
+
}): {
|
|
40
|
+
by: string;
|
|
41
|
+
id: string;
|
|
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;
|
|
49
|
+
/** The masquerader's id if the request carries a genuine borrowed session's token. */
|
|
50
|
+
export declare const borrowedBy: (payload: Payload, headers: Headers | null | undefined) => string | null;
|
|
51
|
+
/**
|
|
52
|
+
* Whether the request is masquerading: it carries the signed state cookie, or a
|
|
53
|
+
* borrowed session's token (so dropping the state cookie doesn't lift read-only).
|
|
54
|
+
*/
|
|
55
|
+
export declare const isMasquerading: (payload: Payload, headers: Headers | null | undefined) => boolean;
|
|
56
|
+
/** The masquerader's id for a request, for audit trails: `masqueraderOf(req)`. */
|
|
57
|
+
export declare const masqueraderOf: (req: Pick<PayloadRequest, "headers" | "payload">) => string | null;
|
|
58
|
+
export declare const masqOptions: (payload: Payload) => ResolvedMasqOptions;
|
|
59
|
+
export declare function cookie(payload: Payload, slug: string, name: string, value: string, seconds: number, path?: string): string;
|
|
60
|
+
/**
|
|
61
|
+
* For your own server actions and route handlers that write through the Local
|
|
62
|
+
* API without the request: refuse while masquerading (read-only masquerade).
|
|
63
|
+
*/
|
|
64
|
+
export declare function assertNotMasquerading(payload: Payload, headers: Headers | null | undefined): void;
|