@extantape/payload-plugin-masq 0.0.0-stage → 0.1.1
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 +155 -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 +155 -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 +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 +37 -0
- package/dist/state.js +97 -0
- package/dist/types.d.ts +80 -0
- package/dist/types.js +1 -0
- package/package.json +79 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EXTANT APE
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,156 @@
|
|
|
1
|
-
#
|
|
1
|
+
# payload-plugin-masq
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Masquerade for [Payload](https://payloadcms.com) 3: an admin signs in as another user to see
|
|
4
|
+
the site and admin exactly as they do, then returns to their own account with one click.
|
|
5
|
+
Built for support and troubleshooting.
|
|
6
|
+
|
|
7
|
+
> **Beta (0.x).** Used in production by Captive Origins. Feedback and issues welcome.
|
|
8
|
+
|
|
9
|
+
## What you get
|
|
10
|
+
|
|
11
|
+
- **Masquerade as this user**: a button on each account page, shown only to people allowed
|
|
12
|
+
to masquerade as that user.
|
|
13
|
+
- **Masquerade area** (`/admin/masquerade`): a "Masquerade as…" autocomplete for quick
|
|
14
|
+
switching, plus a user search with a Masquerade button on every result. Only people allowed to
|
|
15
|
+
masquerade see it, and the search reads with their own access, so it never lists anyone
|
|
16
|
+
they could not already see. The users list gets a Masquerade column with a button per row.
|
|
17
|
+
- **A banner** in the admin (and on your site, with `<MasqueradeBanner />`): who you are
|
|
18
|
+
masquerading as, the time left, and **Return to my account**. Once the borrowed session is
|
|
19
|
+
over, or you're no longer allowed to masquerade as that user, it names nobody and only offers
|
|
20
|
+
the way back.
|
|
21
|
+
- **A real, short session**: the masquerader gets a genuine Payload session of the target
|
|
22
|
+
(the same mechanism as a normal login, sessions included), so every access rule applies
|
|
23
|
+
exactly as for that user. One hour by default, and it can't be refreshed past that.
|
|
24
|
+
- **Safe return**: your own token waits in an httpOnly cookie sent only to the stop endpoint,
|
|
25
|
+
and comes back only if it is still valid and you are still allowed to masquerade. The
|
|
26
|
+
borrowed session is ended when you return.
|
|
27
|
+
- **Audit hooks**: `onStart` (with an optional reason) and `onStop`, and `masqueraderOf(req)`
|
|
28
|
+
so your audit trail can record who really made a change.
|
|
29
|
+
- **Read-only** (default): look everywhere the user can, but change nothing. While
|
|
30
|
+
masquerading, Payload refuses (403) on every collection: create, update, delete (single and
|
|
31
|
+
bulk), restoring a version, unlock, forgot-password and reset-password; and on every global:
|
|
32
|
+
update and restoring a version. That holds over REST, GraphQL and the Local API when you pass
|
|
33
|
+
the request. The borrowed token itself is marked, so clearing the masquerade cookie doesn't
|
|
34
|
+
lift it, whether the token comes in the cookie or an `Authorization` header. Still allowed:
|
|
35
|
+
reads, Payload's own bookkeeping (preferences, document locks), signing in, signing out, and
|
|
36
|
+
the plugin's own return. Not covered: your own endpoints and server actions (call
|
|
37
|
+
`assertNotMasquerading(payload, headers)` there), Local API calls made without the request,
|
|
38
|
+
and email verification links, which Payload runs without hooks. If your site lets signed-in
|
|
39
|
+
users call `/api/payload-jobs/run`, a masquerader can start jobs that are already queued;
|
|
40
|
+
Masq doesn't block that.
|
|
41
|
+
- **A leftover masquerade cookie** lasts up to 24 hours if you never press **Return to my
|
|
42
|
+
account** (for example, the borrowed hour ran out). Until it's cleared, that browser is
|
|
43
|
+
treated as masquerading, so forgot-password and other writes answer 403. Press **Return to my
|
|
44
|
+
account** in the banner to clear it, or wait for the cookie to expire.
|
|
45
|
+
- **`canMasquerade` must answer exactly `true`.** A truthy value, or an error it throws, is a
|
|
46
|
+
no: the endpoints answer 403 and the components show nothing.
|
|
47
|
+
- Never as yourself, no nesting, no public endpoints: masquerading needs a signed-in user the
|
|
48
|
+
rules allow.
|
|
49
|
+
|
|
50
|
+
## Upgrading from 0.1.0
|
|
51
|
+
|
|
52
|
+
Required, once: before or right after upgrading, end every running masquerade. Borrowed
|
|
53
|
+
sessions started by 0.1.0 carry no mark, so with the masquerade cookie cleared they can still
|
|
54
|
+
write, and Payload keeps refreshing them. There is no sound way to tell them apart from normal
|
|
55
|
+
sessions afterwards. A borrowed session is stored on the **target's** account, so signing the
|
|
56
|
+
masquerader out isn't enough. The commands below clear **everyone's** sessions, so every user
|
|
57
|
+
is signed out once and signs in again. (Clearing only the masqueraded users' sessions would be
|
|
58
|
+
enough, but no command for that is given here because none has been tested.)
|
|
59
|
+
|
|
60
|
+
With the Local API (any database adapter; tested), for the default `users` collection:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
await payload.db.updateMany({ collection: 'users', where: {}, data: { sessions: [] } })
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Or on MongoDB from the command line (the same change, not tested here):
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
mongosh "$DATABASE_URI" --eval 'db.users.updateMany({}, { $set: { sessions: [] } })'
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
If your auth collection sets `useSessions: false`, there are no sessions to clear; changing
|
|
73
|
+
`PAYLOAD_SECRET` is then the only way to end those tokens, and it signs everyone out.
|
|
74
|
+
|
|
75
|
+
## On its own, and with others
|
|
76
|
+
|
|
77
|
+
**On its own:** it needs an auth collection (default `users`) and your `canMasquerade`. It works with no other Captive Origins plugin. Auditing is up to your `onStart` and `onStop`.
|
|
78
|
+
|
|
79
|
+
**Works with:**
|
|
80
|
+
- **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.
|
|
81
|
+
- **Hats:** as Hats' design describes, Hats' `blocked(req)` refuses switching while masquerading, and your `canMasquerade` refuses a switched session (`hatsStateOf(user).via`).
|
|
82
|
+
|
|
83
|
+
**Family:** It's part of the **Identity** family (a working draft): plugins designed to sit together for accounts and access.
|
|
84
|
+
|
|
85
|
+
## Install
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
npm install @extantape/payload-plugin-masq
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { masqPlugin } from '@extantape/payload-plugin-masq'
|
|
93
|
+
|
|
94
|
+
export default buildConfig({
|
|
95
|
+
plugins: [
|
|
96
|
+
masqPlugin({
|
|
97
|
+
// Required. Who may masquerade (target absent = may they use masquerade at all).
|
|
98
|
+
canMasquerade: ({ user, target }) => user.role === 'admin',
|
|
99
|
+
onStart: async ({ req, masquerader, target, reason }) => {
|
|
100
|
+
await req.payload.create({
|
|
101
|
+
collection: 'audit-log',
|
|
102
|
+
data: { action: 'masquerade-start', by: masquerader.id, user: target.id, reason },
|
|
103
|
+
req,
|
|
104
|
+
})
|
|
105
|
+
},
|
|
106
|
+
onStop: async ({ req, masqueraderId, targetId, expired }) => {
|
|
107
|
+
/* … */
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
],
|
|
111
|
+
})
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Then run `payload generate:importmap`. Add the banner to your site layout (a Server
|
|
115
|
+
Component) so masqueraders see it outside the admin too:
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
import { MasqueradeBanner } from '@extantape/payload-plugin-masq/rsc'
|
|
119
|
+
|
|
120
|
+
<MasqueradeBanner payload={payload} />
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Options
|
|
124
|
+
|
|
125
|
+
| Option | Default | |
|
|
126
|
+
|---|---|---|
|
|
127
|
+
| `canMasquerade` | (required) | `({ payload, user, target? }) => boolean`. No default: nobody can masquerade until you decide. |
|
|
128
|
+
| `collection` | `'users'` | Auth collection. |
|
|
129
|
+
| `duration` | `3600` | Seconds the borrowed session lasts. |
|
|
130
|
+
| `readOnly` | `true` | Refuse create, update and delete while masquerading. |
|
|
131
|
+
| `requireReason` | `false` | Ask for a reason; passed to `onStart`. |
|
|
132
|
+
| `labelField` | `'email'` | Name shown in the search and banner. |
|
|
133
|
+
| `searchFields` | `['email']` | Fields the search matches. |
|
|
134
|
+
| `startPath` | admin route | Where to go after starting. |
|
|
135
|
+
| `adminBanner` | `true` | Banner in the admin header. |
|
|
136
|
+
| `adminView` | `true` | Masquerade area and nav link. |
|
|
137
|
+
| `listColumn` | `true` | Masquerade column in the users list (added to `defaultColumns`). |
|
|
138
|
+
| `onStart`, `onStop` | | Audit hooks. |
|
|
139
|
+
| `enabled` | `true` | |
|
|
140
|
+
|
|
141
|
+
## Endpoints
|
|
142
|
+
|
|
143
|
+
On the auth collection (`/api/users/…`): `POST /:id/masq` (start, body `{ reason? }`),
|
|
144
|
+
`POST /masq/stop` (return) and `GET /masq/search?q=` (admin search). All need a signed-in
|
|
145
|
+
user that `canMasquerade` allows.
|
|
146
|
+
|
|
147
|
+
## Acknowledgements
|
|
148
|
+
|
|
149
|
+
[payload-plugin-masquerade](https://github.com/manutepowa/payload-plugin-masquerade) came first
|
|
150
|
+
and is worth a look. We built this one because our direction differed in ways too large to
|
|
151
|
+
merge: a short borrowed session that ends on return, restore only for a still-valid masquerader,
|
|
152
|
+
an access-checked admin-only search, a banner on the site as well as the admin, and audit hooks.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { MasqPermissionArgs, ResolvedMasqOptions } from './types.js';
|
|
2
|
+
/** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
|
|
3
|
+
export declare function exactlyTrue(check: () => unknown): Promise<boolean>;
|
|
4
|
+
/** `canMasquerade` answered exactly `true`: a truthy value or an error is a no. */
|
|
5
|
+
export declare const mayMasquerade: (opts: Pick<ResolvedMasqOptions, "canMasquerade">, args: MasqPermissionArgs) => Promise<boolean>;
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
|
|
2
|
+
export async function exactlyTrue(check) {
|
|
3
|
+
try {
|
|
4
|
+
return (await check()) === true;
|
|
5
|
+
}
|
|
6
|
+
catch {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** `canMasquerade` answered exactly `true`: a truthy value or an error is a no. */
|
|
11
|
+
export const mayMasquerade = (opts, args) => exactlyTrue(() => opts.canMasquerade(args));
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
type Props = {
|
|
3
|
+
apiPath: string;
|
|
4
|
+
userId: string;
|
|
5
|
+
requireReason?: boolean;
|
|
6
|
+
label?: string;
|
|
7
|
+
size?: 'small' | 'medium';
|
|
8
|
+
hint?: string | null;
|
|
9
|
+
};
|
|
10
|
+
/** Starts masquerading as a user (asks for a reason when the plugin requires one). */
|
|
11
|
+
export declare function MasqueradeButton({ apiPath, userId, requireReason, label, size, hint }: Props): React.JSX.Element;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Button } from '@payloadcms/ui';
|
|
4
|
+
import { useState } from 'react';
|
|
5
|
+
/** Starts masquerading as a user (asks for a reason when the plugin requires one). */
|
|
6
|
+
export function MasqueradeButton({ apiPath, userId, requireReason = false, label = 'Masquerade as this user', size = 'small', hint }) {
|
|
7
|
+
const [error, setError] = useState(null);
|
|
8
|
+
const [busy, setBusy] = useState(false);
|
|
9
|
+
const [reason, setReason] = useState('');
|
|
10
|
+
const start = async () => {
|
|
11
|
+
if (requireReason && !reason.trim())
|
|
12
|
+
return setError('Say why you are masquerading.');
|
|
13
|
+
setBusy(true);
|
|
14
|
+
setError(null);
|
|
15
|
+
const res = await fetch(`${apiPath}/${encodeURIComponent(userId)}/masq`, {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
credentials: 'include',
|
|
18
|
+
headers: { 'Content-Type': 'application/json' },
|
|
19
|
+
body: JSON.stringify({ reason: reason.trim() || null }),
|
|
20
|
+
});
|
|
21
|
+
const body = (await res.json().catch(() => null));
|
|
22
|
+
if (res.ok) {
|
|
23
|
+
window.location.assign(body?.redirect ?? '/');
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
setError(body?.errors?.[0]?.message ?? 'Could not start masquerading.');
|
|
27
|
+
setBusy(false);
|
|
28
|
+
};
|
|
29
|
+
return (_jsxs("div", { className: "masq-button", style: { display: 'grid', gap: 6, marginBottom: 'var(--base)' }, children: [requireReason && (_jsx("input", { className: "masq-button__reason", placeholder: "Reason (e.g. support ticket)", value: reason, onChange: (e) => setReason(e.target.value), maxLength: 500 })), _jsx(Button, { buttonStyle: "secondary", size: size, disabled: busy, onClick: start, margin: false, children: busy ? 'Starting…' : label }), hint && _jsx("p", { style: { color: 'var(--theme-elevation-500)', fontSize: '0.85em', margin: 0 }, children: hint }), error && _jsx("p", { style: { color: 'var(--theme-error-500)', margin: 0 }, children: error })] }));
|
|
30
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
/** "Masquerade as…": type a name, pick a suggestion (or press Enter for the first), and go. */
|
|
3
|
+
export declare function QuickMasquerade({ apiPath, requireReason }: {
|
|
4
|
+
apiPath: string;
|
|
5
|
+
requireReason: boolean;
|
|
6
|
+
}): React.JSX.Element;
|
|
7
|
+
/** Admin user search for masquerading (results come from the access-checked search endpoint). */
|
|
8
|
+
export declare function MasqueradeSearch({ apiPath, adminRoute, collection, requireReason }: {
|
|
9
|
+
apiPath: string;
|
|
10
|
+
adminRoute: string;
|
|
11
|
+
collection: string;
|
|
12
|
+
requireReason: boolean;
|
|
13
|
+
}): React.JSX.Element;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useState } from 'react';
|
|
4
|
+
import { MasqueradeButton } from './MasqueradeButton.js';
|
|
5
|
+
async function start(apiPath, id, reason) {
|
|
6
|
+
const res = await fetch(`${apiPath}/${encodeURIComponent(id)}/masq`, {
|
|
7
|
+
method: 'POST',
|
|
8
|
+
credentials: 'include',
|
|
9
|
+
headers: { 'Content-Type': 'application/json' },
|
|
10
|
+
body: JSON.stringify({ reason }),
|
|
11
|
+
});
|
|
12
|
+
const body = (await res.json().catch(() => null));
|
|
13
|
+
if (res.ok)
|
|
14
|
+
window.location.assign(body?.redirect ?? '/');
|
|
15
|
+
return res.ok ? null : (body?.errors?.[0]?.message ?? 'Could not start masquerading.');
|
|
16
|
+
}
|
|
17
|
+
/** "Masquerade as…": type a name, pick a suggestion (or press Enter for the first), and go. */
|
|
18
|
+
export function QuickMasquerade({ apiPath, requireReason }) {
|
|
19
|
+
const [q, setQ] = useState('');
|
|
20
|
+
const [reason, setReason] = useState('');
|
|
21
|
+
const [options, setOptions] = useState([]);
|
|
22
|
+
const [active, setActive] = useState(0);
|
|
23
|
+
const [error, setError] = useState(null);
|
|
24
|
+
useEffect(() => {
|
|
25
|
+
if (!q.trim())
|
|
26
|
+
return setOptions([]);
|
|
27
|
+
const ctrl = new AbortController();
|
|
28
|
+
const t = setTimeout(async () => {
|
|
29
|
+
const res = await fetch(`${apiPath}/masq/search?q=${encodeURIComponent(q)}`, { credentials: 'include', signal: ctrl.signal }).catch(() => null);
|
|
30
|
+
if (res?.ok)
|
|
31
|
+
setOptions((await res.json()).docs.filter((r) => r.allowed).slice(0, 8));
|
|
32
|
+
setActive(0);
|
|
33
|
+
}, 200);
|
|
34
|
+
return () => {
|
|
35
|
+
clearTimeout(t);
|
|
36
|
+
ctrl.abort();
|
|
37
|
+
};
|
|
38
|
+
}, [q, apiPath]);
|
|
39
|
+
const go = async (row) => {
|
|
40
|
+
if (!row)
|
|
41
|
+
return;
|
|
42
|
+
if (requireReason && !reason.trim())
|
|
43
|
+
return setError('Say why you are masquerading.');
|
|
44
|
+
setError(await start(apiPath, row.id, reason.trim() || null));
|
|
45
|
+
};
|
|
46
|
+
return (_jsxs("div", { style: { display: 'grid', gap: 6, maxWidth: 760, position: 'relative' }, children: [_jsx("label", { htmlFor: "masq-quick", style: { fontWeight: 600 }, children: "Masquerade as\u2026" }), _jsx("input", { id: "masq-quick", autoFocus: true, role: "combobox", "aria-expanded": options.length > 0, "aria-controls": "masq-quick-list", "aria-activedescendant": options[active] ? `masq-opt-${options[active].id}` : undefined, autoComplete: "off", placeholder: "Start typing a name or email", value: q, onChange: (e) => setQ(e.target.value), onKeyDown: (e) => {
|
|
47
|
+
if (e.key === 'ArrowDown')
|
|
48
|
+
setActive((a) => Math.min(a + 1, options.length - 1));
|
|
49
|
+
else if (e.key === 'ArrowUp')
|
|
50
|
+
setActive((a) => Math.max(a - 1, 0));
|
|
51
|
+
else if (e.key === 'Enter') {
|
|
52
|
+
e.preventDefault();
|
|
53
|
+
void go(options[active]);
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
return;
|
|
57
|
+
e.preventDefault();
|
|
58
|
+
}, style: { padding: '0.6rem 0.8rem', fontSize: '1rem' } }), requireReason && _jsx("input", { placeholder: "Reason (e.g. support ticket)", value: reason, onChange: (e) => setReason(e.target.value), maxLength: 500 }), options.length > 0 && (_jsx("ul", { id: "masq-quick-list", role: "listbox", style: { listStyle: 'none', margin: 0, padding: 4, border: '1px solid var(--theme-elevation-150)', borderRadius: 4, background: 'var(--theme-elevation-0)' }, children: options.map((o, i) => (_jsxs("li", { id: `masq-opt-${o.id}`, role: "option", "aria-selected": i === active, onMouseEnter: () => setActive(i), onMouseDown: (e) => {
|
|
59
|
+
e.preventDefault();
|
|
60
|
+
void go(o);
|
|
61
|
+
}, style: { padding: '6px 8px', cursor: 'pointer', borderRadius: 3, background: i === active ? 'var(--theme-elevation-100)' : undefined }, children: [o.label, o.email && o.email !== o.label && _jsxs("span", { style: { color: 'var(--theme-elevation-500)' }, children: [" \u00B7 ", o.email] })] }, o.id))) })), error && _jsx("p", { style: { color: 'var(--theme-error-500)', margin: 0 }, children: error })] }));
|
|
62
|
+
}
|
|
63
|
+
/** Admin user search for masquerading (results come from the access-checked search endpoint). */
|
|
64
|
+
export function MasqueradeSearch({ apiPath, adminRoute, collection, requireReason }) {
|
|
65
|
+
const [q, setQ] = useState('');
|
|
66
|
+
const [rows, setRows] = useState([]);
|
|
67
|
+
const [state, setState] = useState('idle');
|
|
68
|
+
useEffect(() => {
|
|
69
|
+
const ctrl = new AbortController();
|
|
70
|
+
const t = setTimeout(async () => {
|
|
71
|
+
setState('loading');
|
|
72
|
+
try {
|
|
73
|
+
const res = await fetch(`${apiPath}/masq/search?q=${encodeURIComponent(q)}`, { credentials: 'include', signal: ctrl.signal });
|
|
74
|
+
if (!res.ok)
|
|
75
|
+
throw new Error(String(res.status));
|
|
76
|
+
setRows((await res.json()).docs);
|
|
77
|
+
setState('idle');
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
if (e.name !== 'AbortError')
|
|
81
|
+
setState('error');
|
|
82
|
+
}
|
|
83
|
+
}, 250);
|
|
84
|
+
return () => {
|
|
85
|
+
clearTimeout(t);
|
|
86
|
+
ctrl.abort();
|
|
87
|
+
};
|
|
88
|
+
}, [q, apiPath]);
|
|
89
|
+
return (_jsxs("div", { style: { display: 'grid', gap: 'var(--base)', maxWidth: 760 }, children: [_jsx("input", { type: "search", placeholder: "Search users", value: q, onChange: (e) => setQ(e.target.value), style: { padding: '0.6rem 0.8rem', fontSize: '1rem' }, "aria-label": "Search users" }), state === 'error' && _jsx("p", { style: { color: 'var(--theme-error-500)' }, children: "Search failed." }), _jsxs("ul", { style: { listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 8 }, children: [rows.map((r) => (_jsxs("li", { style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: 12, borderBottom: '1px solid var(--theme-elevation-100)', paddingBottom: 8 }, children: [_jsxs("span", { children: [_jsx("a", { href: `${adminRoute}/collections/${collection}/${r.id}`, children: r.label }), r.email && r.email !== r.label && _jsxs("span", { style: { color: 'var(--theme-elevation-500)' }, children: [" \u00B7 ", r.email] })] }), r.allowed ? _jsx(MasqueradeButton, { apiPath: apiPath, userId: r.id, requireReason: requireReason, label: "Masquerade" }) : _jsx("span", { style: { color: 'var(--theme-elevation-500)' }, children: "Not allowed" })] }, r.id))), state === 'idle' && rows.length === 0 && _jsx("li", { style: { color: 'var(--theme-elevation-500)' }, children: "No users found." })] })] }));
|
|
90
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { useState } from 'react';
|
|
4
|
+
/** Stops masquerading and returns to the masquerader's own account. */
|
|
5
|
+
export function ReturnButton({ stopPath, label = 'Return to my account', style }) {
|
|
6
|
+
const [busy, setBusy] = useState(false);
|
|
7
|
+
return (_jsx("button", { type: "button", disabled: busy, style: { border: '1px solid rgba(255,255,255,0.7)', background: '#fff', color: '#7c2d12', borderRadius: 6, padding: '0.25rem 0.75rem', fontWeight: 600, cursor: 'pointer', ...style }, onClick: async () => {
|
|
8
|
+
setBusy(true);
|
|
9
|
+
const res = await fetch(stopPath, { method: 'POST', credentials: 'include' });
|
|
10
|
+
const body = (await res.json().catch(() => null));
|
|
11
|
+
window.location.assign(body?.redirect ?? '/');
|
|
12
|
+
}, children: busy ? 'Returning…' : label }));
|
|
13
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type Endpoint } from 'payload';
|
|
2
|
+
/** POST /api/<collection>/:id/masq { reason? } */
|
|
3
|
+
export declare const startEndpoint: Endpoint;
|
|
4
|
+
/** POST /api/<collection>/masq/stop: end the borrowed session and restore the masquerader's own. */
|
|
5
|
+
export declare const stopEndpoint: Endpoint;
|
|
6
|
+
/**
|
|
7
|
+
* GET /api/<collection>/masq/search?q=&page=: the admin user search. Only for
|
|
8
|
+
* people allowed to masquerade at all, and it reads with their own access, so it
|
|
9
|
+
* never shows a user they could not already see. Lists only users they may
|
|
10
|
+
* masquerade as.
|
|
11
|
+
*/
|
|
12
|
+
export declare const searchEndpoint: Endpoint;
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { addDataAndFileToRequest, APIError, getFieldsToSign, jwtSign } from 'payload';
|
|
2
|
+
import { addSessionToUser, parseCookies } from 'payload/shared';
|
|
3
|
+
import { BORROWED_CLAIM, borrowedClaim, cookie, encodeState, isMasquerading, masqOptions, masqStateOf, RETURN_COOKIE, STATE_COOKIE } from './state.js';
|
|
4
|
+
import { mayMasquerade } from './access.js';
|
|
5
|
+
const STATE_SECONDS = 24 * 60 * 60;
|
|
6
|
+
const json = (body, cookies = [], status = 200) => {
|
|
7
|
+
const headers = new Headers({ 'Content-Type': 'application/json' });
|
|
8
|
+
for (const c of cookies)
|
|
9
|
+
headers.append('Set-Cookie', c);
|
|
10
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
11
|
+
};
|
|
12
|
+
const tokenCookie = (req) => `${req.payload.config.cookiePrefix}-token`;
|
|
13
|
+
/** The signed-in user of the masquerade collection, or a 403. */
|
|
14
|
+
function signedIn(req) {
|
|
15
|
+
const { collection } = masqOptions(req.payload);
|
|
16
|
+
if (!req.user || req.user.collection !== collection)
|
|
17
|
+
throw new APIError('Sign in first.', 401, undefined, true);
|
|
18
|
+
return req.user;
|
|
19
|
+
}
|
|
20
|
+
/** POST /api/<collection>/:id/masq { reason? } */
|
|
21
|
+
export const startEndpoint = {
|
|
22
|
+
path: '/:id/masq',
|
|
23
|
+
method: 'post',
|
|
24
|
+
handler: async (req) => {
|
|
25
|
+
const opts = masqOptions(req.payload);
|
|
26
|
+
const user = signedIn(req);
|
|
27
|
+
if (isMasquerading(req.payload, req.headers))
|
|
28
|
+
throw new APIError('Stop masquerading first.', 400, undefined, true);
|
|
29
|
+
const own = parseCookies(req.headers).get(tokenCookie(req));
|
|
30
|
+
if (!own)
|
|
31
|
+
throw new APIError('Masquerade needs a browser sign-in.', 400, undefined, true);
|
|
32
|
+
const id = String(req.routeParams?.id ?? '');
|
|
33
|
+
if (!id || id === String(user.id))
|
|
34
|
+
throw new APIError('Choose another user.', 400, undefined, true);
|
|
35
|
+
await addDataAndFileToRequest(req);
|
|
36
|
+
const reason = typeof req.data?.reason === 'string' ? req.data.reason.trim().slice(0, 500) || null : null;
|
|
37
|
+
if (opts.requireReason && !reason)
|
|
38
|
+
throw new APIError('Say why you are masquerading.', 400, undefined, true);
|
|
39
|
+
const target = (await req.payload.findByID({
|
|
40
|
+
collection: opts.collection,
|
|
41
|
+
id,
|
|
42
|
+
depth: 0,
|
|
43
|
+
overrideAccess: true,
|
|
44
|
+
showHiddenFields: true,
|
|
45
|
+
disableErrors: true,
|
|
46
|
+
req,
|
|
47
|
+
}));
|
|
48
|
+
if (!target)
|
|
49
|
+
throw new APIError('User not found.', 404, undefined, true);
|
|
50
|
+
if (!(await mayMasquerade(opts, { payload: req.payload, user, target })))
|
|
51
|
+
throw new APIError('You may not masquerade as this user.', 403, undefined, true);
|
|
52
|
+
const collectionConfig = req.payload.collections[opts.collection].config;
|
|
53
|
+
const { sid } = await addSessionToUser({ collectionConfig, payload: req.payload, req, user: target });
|
|
54
|
+
const { token } = await jwtSign({
|
|
55
|
+
// Marked as borrowed, so it stays read-only and can't be refreshed even without the state cookie.
|
|
56
|
+
fieldsToSign: { ...getFieldsToSign({ collectionConfig, email: String(target.email ?? ''), sid, user: target }), [BORROWED_CLAIM]: String(user.id) },
|
|
57
|
+
secret: req.payload.secret,
|
|
58
|
+
tokenExpiration: opts.duration,
|
|
59
|
+
});
|
|
60
|
+
const now = Date.now();
|
|
61
|
+
const state = { by: String(user.id), as: id, at: new Date(now).toISOString(), until: new Date(now + opts.duration * 1000).toISOString() };
|
|
62
|
+
await opts.onStart?.({ req, masquerader: user, target, reason });
|
|
63
|
+
return json({ ok: true, redirect: opts.startPath }, [
|
|
64
|
+
cookie(req.payload, opts.collection, tokenCookie(req), token, opts.duration),
|
|
65
|
+
// The masquerader's own token goes back only to the stop endpoint.
|
|
66
|
+
cookie(req.payload, opts.collection, RETURN_COOKIE, own, STATE_SECONDS, `${opts.apiRoute}/${opts.collection}/masq/stop`),
|
|
67
|
+
cookie(req.payload, opts.collection, STATE_COOKIE, encodeState(req.payload.secret, state), STATE_SECONDS),
|
|
68
|
+
]);
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
/** POST /api/<collection>/masq/stop: end the borrowed session and restore the masquerader's own. */
|
|
72
|
+
export const stopEndpoint = {
|
|
73
|
+
path: '/masq/stop',
|
|
74
|
+
method: 'post',
|
|
75
|
+
handler: async (req) => {
|
|
76
|
+
const opts = masqOptions(req.payload);
|
|
77
|
+
const state = masqStateOf(req.payload, req.headers);
|
|
78
|
+
// Our own writes (and onStop's) are allowed even in read-only mode.
|
|
79
|
+
req.context = { ...req.context, masqInternal: true };
|
|
80
|
+
const own = parseCookies(req.headers).get(RETURN_COOKIE);
|
|
81
|
+
const stopPath = `${opts.apiRoute}/${opts.collection}/masq/stop`;
|
|
82
|
+
const clear = [cookie(req.payload, opts.collection, RETURN_COOKIE, '', -1, stopPath), cookie(req.payload, opts.collection, STATE_COOKIE, '', -1)];
|
|
83
|
+
// End the borrowed session if it is still alive: named by the state cookie, or, if that
|
|
84
|
+
// cookie is gone, by the borrowed token's own claim.
|
|
85
|
+
const borrowed = req.user;
|
|
86
|
+
// 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);
|
|
88
|
+
const claimedBy = claim && borrowed && claim.id === String(borrowed.id) ? claim.by : null;
|
|
89
|
+
const live = Boolean(borrowed?.collection === opts.collection && (state ? String(borrowed.id) === state.as : claimedBy));
|
|
90
|
+
if (live && borrowed?._sid) {
|
|
91
|
+
const doc = (await req.payload.findByID({ collection: opts.collection, id: borrowed.id, depth: 0, overrideAccess: true, showHiddenFields: true, req }));
|
|
92
|
+
await req.payload.db.updateOne({
|
|
93
|
+
collection: opts.collection,
|
|
94
|
+
id: borrowed.id,
|
|
95
|
+
data: { sessions: (doc.sessions ?? []).filter((s) => s.id !== borrowed._sid) },
|
|
96
|
+
req,
|
|
97
|
+
returning: false,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
// Restore only a still-valid token of the same masquerader who may still masquerade.
|
|
101
|
+
const restored = state && own ? await req.payload.auth({ headers: new Headers({ Authorization: `JWT ${own}` }) }).catch(() => null) : null;
|
|
102
|
+
const user = (restored?.user ?? null);
|
|
103
|
+
const ok = Boolean(state && user && String(user.id) === state.by && (await mayMasquerade(opts, { payload: req.payload, user: user })));
|
|
104
|
+
if (state)
|
|
105
|
+
await opts.onStop?.({ req, masqueraderId: state.by, targetId: state.as, expired: !live, restored: ok });
|
|
106
|
+
else if (live && claimedBy)
|
|
107
|
+
await opts.onStop?.({ req, masqueraderId: claimedBy, targetId: String(borrowed.id), expired: false, restored: false });
|
|
108
|
+
if (!ok)
|
|
109
|
+
return json({ ok: true, restored: false, redirect: `${opts.adminRoute}/login` }, [...clear, cookie(req.payload, opts.collection, tokenCookie(req), '', -1)]);
|
|
110
|
+
const seconds = req.payload.collections[opts.collection].config.auth.tokenExpiration;
|
|
111
|
+
return json({ ok: true, restored: true, redirect: `${opts.adminRoute}/collections/${opts.collection}/${state.as}` }, [
|
|
112
|
+
...clear,
|
|
113
|
+
cookie(req.payload, opts.collection, tokenCookie(req), own, seconds),
|
|
114
|
+
]);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* GET /api/<collection>/masq/search?q=&page=: the admin user search. Only for
|
|
119
|
+
* people allowed to masquerade at all, and it reads with their own access, so it
|
|
120
|
+
* never shows a user they could not already see. Lists only users they may
|
|
121
|
+
* masquerade as.
|
|
122
|
+
*/
|
|
123
|
+
export const searchEndpoint = {
|
|
124
|
+
path: '/masq/search',
|
|
125
|
+
method: 'get',
|
|
126
|
+
handler: async (req) => {
|
|
127
|
+
const opts = masqOptions(req.payload);
|
|
128
|
+
const user = signedIn(req);
|
|
129
|
+
if (!(await mayMasquerade(opts, { payload: req.payload, user })))
|
|
130
|
+
throw new APIError('Not allowed.', 403, undefined, true);
|
|
131
|
+
const q = String(req.searchParams?.get('q') ?? '').trim().slice(0, 100);
|
|
132
|
+
const page = Math.max(1, Number(req.searchParams?.get('page')) || 1);
|
|
133
|
+
const where = {
|
|
134
|
+
and: [{ id: { not_equals: user.id } }, ...(q ? [{ or: opts.searchFields.map((f) => ({ [f]: { like: q } })) }] : [])],
|
|
135
|
+
};
|
|
136
|
+
const found = await req.payload.find({
|
|
137
|
+
collection: opts.collection,
|
|
138
|
+
where,
|
|
139
|
+
page,
|
|
140
|
+
limit: 20,
|
|
141
|
+
depth: 0,
|
|
142
|
+
sort: opts.labelField,
|
|
143
|
+
overrideAccess: false,
|
|
144
|
+
user: req.user,
|
|
145
|
+
req,
|
|
146
|
+
});
|
|
147
|
+
const docs = await Promise.all(found.docs.map(async (d) => ({
|
|
148
|
+
id: String(d.id),
|
|
149
|
+
label: String(d[opts.labelField] ?? d.email ?? d.id),
|
|
150
|
+
email: d.email ?? null,
|
|
151
|
+
allowed: await mayMasquerade(opts, { payload: req.payload, user, target: d }),
|
|
152
|
+
})));
|
|
153
|
+
return json({ docs, page: found.page, totalPages: found.totalPages, totalDocs: found.totalDocs });
|
|
154
|
+
},
|
|
155
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { masqPlugin, READ_ONLY_MESSAGE } from './plugin.js';
|
|
2
|
+
export { assertNotMasquerading, masqStateOf, masqueraderOf, decodeState, STATE_COOKIE } from './state.js';
|
|
3
|
+
export { searchEndpoint, startEndpoint, stopEndpoint } from './endpoints.js';
|
|
4
|
+
export type { MasqPermissionArgs, MasqPluginOptions, MasqStartArgs, MasqState, MasqStopArgs, MasqUser, ResolvedMasqOptions } from './types.js';
|
package/dist/index.js
ADDED
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type Plugin } from 'payload';
|
|
2
|
+
import type { MasqPluginOptions } from './types.js';
|
|
3
|
+
export declare const READ_ONLY_MESSAGE = "Masquerade is read-only: nothing can be created, changed or deleted while masquerading.";
|
|
4
|
+
/**
|
|
5
|
+
* Masquerade: an admin signs in as another user to see what they see.
|
|
6
|
+
*
|
|
7
|
+
* - The masquerader gets a real, short Payload session of the target (the same
|
|
8
|
+
* session machinery as a normal login), so every access rule applies exactly
|
|
9
|
+
* as for that user. Default one hour.
|
|
10
|
+
* - Their own token waits in an httpOnly cookie sent only to the stop
|
|
11
|
+
* endpoint, and comes back only if it is still valid and they may still
|
|
12
|
+
* masquerade. The borrowed session is ended on return.
|
|
13
|
+
* - A signed cookie records who is masquerading as whom, for the banner and
|
|
14
|
+
* for audit trails (`masqueraderOf(req)`).
|
|
15
|
+
* - The admin gets a "Masquerade as this user" button on each user, a
|
|
16
|
+
* Masquerade view with a user search (only for people allowed to
|
|
17
|
+
* masquerade, reading with their own access), and a banner with
|
|
18
|
+
* "Return to my account". Put `<MasqueradeBanner />` in your site layout too.
|
|
19
|
+
*/
|
|
20
|
+
export declare const masqPlugin: (options: MasqPluginOptions) => Plugin;
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { searchEndpoint, startEndpoint, stopEndpoint } from './endpoints.js';
|
|
3
|
+
import { borrowedBy, isMasquerading } from './state.js';
|
|
4
|
+
/** Payload's own bookkeeping, written while simply looking around the admin. */
|
|
5
|
+
const BOOKKEEPING = new Set(['payload-preferences', 'payload-locked-documents']);
|
|
6
|
+
export const READ_ONLY_MESSAGE = 'Masquerade is read-only: nothing can be created, changed or deleted while masquerading.';
|
|
7
|
+
/**
|
|
8
|
+
* Every collection operation in Payload 3.92 that writes and runs `beforeOperation`. Login
|
|
9
|
+
* (it only records the sign-in) and refresh (refused separately) are left out.
|
|
10
|
+
*/
|
|
11
|
+
const COLLECTION_WRITES = new Set(['create', 'update', 'delete', 'restoreVersion', 'unlock', 'forgotPassword', 'resetPassword']);
|
|
12
|
+
/** Global operations that write. A global restore skips `beforeChange`, so the guard sits here. */
|
|
13
|
+
const GLOBAL_WRITES = new Set(['update', 'restoreVersion']);
|
|
14
|
+
/** Read-only masquerade: refuse writes while masquerading (the plugin's own writes are marked internal). */
|
|
15
|
+
const readOnlyGuard = ({ args, operation, req }) => {
|
|
16
|
+
if (req.context?.masqInternal)
|
|
17
|
+
return args;
|
|
18
|
+
if (COLLECTION_WRITES.has(operation) && isMasquerading(req.payload, req.headers))
|
|
19
|
+
throw new APIError(READ_ONLY_MESSAGE, 403, undefined, true);
|
|
20
|
+
return args;
|
|
21
|
+
};
|
|
22
|
+
const globalReadOnlyGuard = ({ args, operation, req }) => {
|
|
23
|
+
if (req.context?.masqInternal)
|
|
24
|
+
return args;
|
|
25
|
+
if (GLOBAL_WRITES.has(operation) && isMasquerading(req.payload, req.headers))
|
|
26
|
+
throw new APIError(READ_ONLY_MESSAGE, 403, undefined, true);
|
|
27
|
+
return args;
|
|
28
|
+
};
|
|
29
|
+
/** A borrowed session ends on time: it can't be refreshed (the admin refreshes tokens while you're active). */
|
|
30
|
+
const noBorrowedRefresh = ({ args, operation, req }) => {
|
|
31
|
+
if (operation === 'refresh' && borrowedBy(req.payload, req.headers))
|
|
32
|
+
throw new APIError('A masquerade session can’t be extended.', 403, undefined, true);
|
|
33
|
+
return args;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Masquerade: an admin signs in as another user to see what they see.
|
|
37
|
+
*
|
|
38
|
+
* - The masquerader gets a real, short Payload session of the target (the same
|
|
39
|
+
* session machinery as a normal login), so every access rule applies exactly
|
|
40
|
+
* as for that user. Default one hour.
|
|
41
|
+
* - Their own token waits in an httpOnly cookie sent only to the stop
|
|
42
|
+
* endpoint, and comes back only if it is still valid and they may still
|
|
43
|
+
* masquerade. The borrowed session is ended on return.
|
|
44
|
+
* - A signed cookie records who is masquerading as whom, for the banner and
|
|
45
|
+
* for audit trails (`masqueraderOf(req)`).
|
|
46
|
+
* - The admin gets a "Masquerade as this user" button on each user, a
|
|
47
|
+
* Masquerade view with a user search (only for people allowed to
|
|
48
|
+
* masquerade, reading with their own access), and a banner with
|
|
49
|
+
* "Return to my account". Put `<MasqueradeBanner />` in your site layout too.
|
|
50
|
+
*/
|
|
51
|
+
export const masqPlugin = (options) => (config) => {
|
|
52
|
+
if (options.enabled === false)
|
|
53
|
+
return config;
|
|
54
|
+
const collection = options.collection ?? 'users';
|
|
55
|
+
const adminRoute = config.routes?.admin ?? '/admin';
|
|
56
|
+
const resolved = {
|
|
57
|
+
collection,
|
|
58
|
+
canMasquerade: options.canMasquerade,
|
|
59
|
+
duration: options.duration ?? 3600,
|
|
60
|
+
readOnly: options.readOnly ?? true,
|
|
61
|
+
requireReason: options.requireReason ?? false,
|
|
62
|
+
labelField: options.labelField ?? 'email',
|
|
63
|
+
searchFields: options.searchFields ?? ['email'],
|
|
64
|
+
startPath: options.startPath ?? adminRoute,
|
|
65
|
+
adminBanner: options.adminBanner ?? true,
|
|
66
|
+
adminView: options.adminView ?? true,
|
|
67
|
+
listColumn: options.listColumn ?? true,
|
|
68
|
+
enabled: true,
|
|
69
|
+
onStart: options.onStart,
|
|
70
|
+
onStop: options.onStop,
|
|
71
|
+
apiRoute: config.routes?.api ?? '/api',
|
|
72
|
+
adminRoute,
|
|
73
|
+
};
|
|
74
|
+
if (!(config.collections ?? []).some((c) => c.slug === collection))
|
|
75
|
+
throw new Error(`payload-plugin-masq: no collection "${collection}"`);
|
|
76
|
+
const components = config.admin?.components ?? {};
|
|
77
|
+
const globals = resolved.readOnly
|
|
78
|
+
? (config.globals ?? []).map((g) => ({
|
|
79
|
+
...g,
|
|
80
|
+
hooks: {
|
|
81
|
+
...g.hooks,
|
|
82
|
+
beforeOperation: [...(g.hooks?.beforeOperation ?? []), globalReadOnlyGuard],
|
|
83
|
+
beforeChange: [
|
|
84
|
+
...(g.hooks?.beforeChange ?? []),
|
|
85
|
+
(({ data, req }) => {
|
|
86
|
+
if (!req.context?.masqInternal && isMasquerading(req.payload, req.headers))
|
|
87
|
+
throw new APIError(READ_ONLY_MESSAGE, 403, undefined, true);
|
|
88
|
+
return data;
|
|
89
|
+
}),
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
}))
|
|
93
|
+
: config.globals;
|
|
94
|
+
return {
|
|
95
|
+
...config,
|
|
96
|
+
globals,
|
|
97
|
+
custom: { ...config.custom, masq: resolved },
|
|
98
|
+
admin: {
|
|
99
|
+
...config.admin,
|
|
100
|
+
components: {
|
|
101
|
+
...components,
|
|
102
|
+
header: [...(components.header ?? []), ...(resolved.adminBanner ? ['@extantape/payload-plugin-masq/rsc#AdminMasqueradeBanner'] : [])],
|
|
103
|
+
afterNavLinks: [...(components.afterNavLinks ?? []), ...(resolved.adminView ? ['@extantape/payload-plugin-masq/rsc#MasqueradeNavLink'] : [])],
|
|
104
|
+
views: {
|
|
105
|
+
...components.views,
|
|
106
|
+
...(resolved.adminView ? { masquerade: { Component: '@extantape/payload-plugin-masq/rsc#MasqueradeView', path: '/masquerade' } } : {}),
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
collections: (config.collections ?? []).map((c) => {
|
|
111
|
+
const guarded = resolved.readOnly && !BOOKKEEPING.has(c.slug);
|
|
112
|
+
const hooks = guarded ? { ...c.hooks, beforeOperation: [...(c.hooks?.beforeOperation ?? []), readOnlyGuard] } : c.hooks;
|
|
113
|
+
if (c.slug !== collection)
|
|
114
|
+
return { ...c, hooks };
|
|
115
|
+
const columns = c.admin?.defaultColumns;
|
|
116
|
+
return {
|
|
117
|
+
...c,
|
|
118
|
+
hooks: { ...hooks, beforeOperation: [...(hooks?.beforeOperation ?? []), noBorrowedRefresh] },
|
|
119
|
+
admin: resolved.listColumn && columns ? { ...c.admin, defaultColumns: [...columns, 'masq'] } : c.admin,
|
|
120
|
+
endpoints: [stopEndpoint, searchEndpoint, startEndpoint, ...(c.endpoints || [])],
|
|
121
|
+
fields: [
|
|
122
|
+
{
|
|
123
|
+
name: 'masq',
|
|
124
|
+
type: 'ui',
|
|
125
|
+
label: 'Masquerade',
|
|
126
|
+
admin: {
|
|
127
|
+
position: 'sidebar',
|
|
128
|
+
components: { Field: '@extantape/payload-plugin-masq/rsc#MasqueradeField', Cell: '@extantape/payload-plugin-masq/rsc#MasqueradeCell' },
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
...c.fields,
|
|
132
|
+
],
|
|
133
|
+
};
|
|
134
|
+
}),
|
|
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,37 @@
|
|
|
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 declare function borrowedClaim(payload: Payload, headers: Headers | null | undefined): {
|
|
19
|
+
by: string;
|
|
20
|
+
id: string;
|
|
21
|
+
} | null;
|
|
22
|
+
/** The masquerader's id if the request carries a genuine borrowed session's token. */
|
|
23
|
+
export declare const borrowedBy: (payload: Payload, headers: Headers | null | undefined) => string | null;
|
|
24
|
+
/**
|
|
25
|
+
* Whether the request is masquerading: it carries the signed state cookie, or a
|
|
26
|
+
* borrowed session's token (so dropping the state cookie doesn't lift read-only).
|
|
27
|
+
*/
|
|
28
|
+
export declare const isMasquerading: (payload: Payload, headers: Headers | null | undefined) => boolean;
|
|
29
|
+
/** The masquerader's id for a request, for audit trails: `masqueraderOf(req)`. */
|
|
30
|
+
export declare const masqueraderOf: (req: Pick<PayloadRequest, "headers" | "payload">) => string | null;
|
|
31
|
+
export declare const masqOptions: (payload: Payload) => ResolvedMasqOptions;
|
|
32
|
+
export declare function cookie(payload: Payload, slug: string, name: string, value: string, seconds: number, path?: string): string;
|
|
33
|
+
/**
|
|
34
|
+
* For your own server actions and route handlers that write through the Local
|
|
35
|
+
* API without the request: refuse while masquerading (read-only masquerade).
|
|
36
|
+
*/
|
|
37
|
+
export declare function assertNotMasquerading(payload: Payload, headers: Headers | null | undefined): void;
|
package/dist/state.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { generateCookie, parseCookies } from 'payload/shared';
|
|
3
|
+
export const STATE_COOKIE = 'payload-masq';
|
|
4
|
+
export const RETURN_COOKIE = 'payload-masq-return';
|
|
5
|
+
const mac = (secret, body) => crypto.createHmac('sha256', secret).update(`masq:${body}`).digest('base64url');
|
|
6
|
+
export function encodeState(secret, state) {
|
|
7
|
+
const body = Buffer.from(JSON.stringify(state)).toString('base64url');
|
|
8
|
+
return `${body}.${mac(secret, body)}`;
|
|
9
|
+
}
|
|
10
|
+
/** The state from a signed cookie value, or null if missing, forged or malformed. */
|
|
11
|
+
export function decodeState(secret, raw) {
|
|
12
|
+
if (!raw)
|
|
13
|
+
return null;
|
|
14
|
+
const [body, sig] = raw.split('.');
|
|
15
|
+
if (!body || !sig)
|
|
16
|
+
return null;
|
|
17
|
+
const expected = Buffer.from(mac(secret, body));
|
|
18
|
+
const given = Buffer.from(sig);
|
|
19
|
+
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given))
|
|
20
|
+
return null;
|
|
21
|
+
try {
|
|
22
|
+
const s = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
|
|
23
|
+
return s.by && s.as && s.at && s.until ? s : null;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** The active masquerade of a request (from its cookies), if any. */
|
|
30
|
+
export const masqStateOf = (payload, headers) => headers ? decodeState(payload.secret, parseCookies(headers).get(STATE_COOKIE)) : null;
|
|
31
|
+
/** Claim that marks a borrowed session's token, with the masquerader's id. */
|
|
32
|
+
export const BORROWED_CLAIM = 'masqBy';
|
|
33
|
+
/**
|
|
34
|
+
* The claim of a borrowed masquerade session in the request's Payload token (cookie or
|
|
35
|
+
* Authorization header): the masquerader (`by`) and the account the token signs in as
|
|
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.
|
|
38
|
+
*/
|
|
39
|
+
export function borrowedClaim(payload, headers) {
|
|
40
|
+
if (!headers || !payload.secret)
|
|
41
|
+
return null;
|
|
42
|
+
const auth = headers.get('Authorization') ?? '';
|
|
43
|
+
const tokens = [parseCookies(headers).get(`${payload.config?.cookiePrefix ?? 'payload'}-token`), auth.replace(/^(JWT|Bearer) /, '')];
|
|
44
|
+
for (const token of tokens) {
|
|
45
|
+
const [head, body, sig] = token?.split('.') ?? [];
|
|
46
|
+
if (!head || !body || !sig)
|
|
47
|
+
continue;
|
|
48
|
+
const expected = Buffer.from(crypto.createHmac('sha256', payload.secret).update(`${head}.${body}`).digest('base64url'));
|
|
49
|
+
const given = Buffer.from(sig);
|
|
50
|
+
if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given))
|
|
51
|
+
continue;
|
|
52
|
+
try {
|
|
53
|
+
if (JSON.parse(Buffer.from(head, 'base64url').toString('utf8')).alg !== 'HS256')
|
|
54
|
+
continue;
|
|
55
|
+
const claims = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
|
|
56
|
+
const by = claims[BORROWED_CLAIM];
|
|
57
|
+
if (typeof by === 'string' && by)
|
|
58
|
+
return { by, id: String(claims.id ?? '') };
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// Not a JWT we can read: not a borrowed session.
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
/** The masquerader's id if the request carries a genuine borrowed session's token. */
|
|
67
|
+
export const borrowedBy = (payload, headers) => borrowedClaim(payload, headers)?.by ?? null;
|
|
68
|
+
/**
|
|
69
|
+
* Whether the request is masquerading: it carries the signed state cookie, or a
|
|
70
|
+
* borrowed session's token (so dropping the state cookie doesn't lift read-only).
|
|
71
|
+
*/
|
|
72
|
+
export const isMasquerading = (payload, headers) => Boolean(masqStateOf(payload, headers) || borrowedBy(payload, headers));
|
|
73
|
+
/** The masquerader's id for a request, for audit trails: `masqueraderOf(req)`. */
|
|
74
|
+
export const masqueraderOf = (req) => masqStateOf(req.payload, req.headers)?.by ?? null;
|
|
75
|
+
export const masqOptions = (payload) => payload.config.custom?.masq;
|
|
76
|
+
export function cookie(payload, slug, name, value, seconds, path = '/') {
|
|
77
|
+
const auth = payload.collections[slug].config.auth;
|
|
78
|
+
return generateCookie({
|
|
79
|
+
name,
|
|
80
|
+
value,
|
|
81
|
+
path,
|
|
82
|
+
httpOnly: true,
|
|
83
|
+
secure: auth.cookies.secure,
|
|
84
|
+
sameSite: 'Lax',
|
|
85
|
+
domain: auth.cookies.domain ?? undefined,
|
|
86
|
+
expires: new Date(Date.now() + seconds * 1000),
|
|
87
|
+
returnCookieAsObject: false,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* For your own server actions and route handlers that write through the Local
|
|
92
|
+
* API without the request: refuse while masquerading (read-only masquerade).
|
|
93
|
+
*/
|
|
94
|
+
export function assertNotMasquerading(payload, headers) {
|
|
95
|
+
if (payload.config.custom?.masq?.readOnly !== false && isMasquerading(payload, headers))
|
|
96
|
+
throw new Error('Masquerade is read-only: nothing can be created, changed or deleted while masquerading.');
|
|
97
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { Payload, PayloadRequest } from 'payload';
|
|
2
|
+
/** A user document of the masquerade collection (any auth collection). */
|
|
3
|
+
export type MasqUser = {
|
|
4
|
+
id: number | string;
|
|
5
|
+
email?: string | null;
|
|
6
|
+
} & Record<string, unknown>;
|
|
7
|
+
export type MasqPermissionArgs = {
|
|
8
|
+
payload: Payload;
|
|
9
|
+
/** The signed-in user who wants to masquerade. */
|
|
10
|
+
user: MasqUser;
|
|
11
|
+
/** The account to masquerade as; absent when asking whether `user` may use masquerade at all (search, menu). */
|
|
12
|
+
target?: MasqUser;
|
|
13
|
+
};
|
|
14
|
+
export type MasqStartArgs = {
|
|
15
|
+
req: PayloadRequest;
|
|
16
|
+
masquerader: MasqUser;
|
|
17
|
+
target: MasqUser;
|
|
18
|
+
reason: string | null;
|
|
19
|
+
};
|
|
20
|
+
export type MasqStopArgs = {
|
|
21
|
+
req: PayloadRequest;
|
|
22
|
+
masqueraderId: string;
|
|
23
|
+
targetId: string;
|
|
24
|
+
/** The borrowed session had already ended (expired or signed out). */
|
|
25
|
+
expired: boolean;
|
|
26
|
+
/** The masquerader's own session was restored. */
|
|
27
|
+
restored: boolean;
|
|
28
|
+
};
|
|
29
|
+
export type MasqPluginOptions = {
|
|
30
|
+
/** Auth collection to masquerade in. Default `users`. */
|
|
31
|
+
collection?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Who may masquerade, and as whom. Required: there is no default, so nobody
|
|
34
|
+
* can masquerade until you decide. Masquerading as oneself and nesting are
|
|
35
|
+
* always refused.
|
|
36
|
+
*/
|
|
37
|
+
canMasquerade: (args: MasqPermissionArgs) => boolean | Promise<boolean>;
|
|
38
|
+
/** Length of the borrowed session in seconds. Default 3600 (one hour). */
|
|
39
|
+
duration?: number;
|
|
40
|
+
/**
|
|
41
|
+
* Look, don't touch: refuse create, update and delete while masquerading, everywhere
|
|
42
|
+
* Payload runs (REST, GraphQL, admin, Local API with the request). Payload's own
|
|
43
|
+
* bookkeeping (preferences, document locks) still works so the admin behaves normally.
|
|
44
|
+
* Default true. For your own server actions, call `assertNotMasquerading(payload, headers)`.
|
|
45
|
+
*/
|
|
46
|
+
readOnly?: boolean;
|
|
47
|
+
/** Ask for a reason before starting; it is passed to `onStart`. Default false. */
|
|
48
|
+
requireReason?: boolean;
|
|
49
|
+
/** Field shown as each user's name in the search. Default `email`. */
|
|
50
|
+
labelField?: string;
|
|
51
|
+
/** Fields the admin search matches (`like`). Default `['email']`. */
|
|
52
|
+
searchFields?: string[];
|
|
53
|
+
/** Where to go after starting. Default: the admin dashboard. */
|
|
54
|
+
startPath?: string;
|
|
55
|
+
/** Add the banner to the admin header. Default true. */
|
|
56
|
+
adminBanner?: boolean;
|
|
57
|
+
/** Show a Masquerade column (button per row) in the users list by default. Default true. */
|
|
58
|
+
listColumn?: boolean;
|
|
59
|
+
/** Add the "Masquerade" view (admin-only user search) and its nav link. Default true. */
|
|
60
|
+
adminView?: boolean;
|
|
61
|
+
onStart?: (args: MasqStartArgs) => void | Promise<void>;
|
|
62
|
+
onStop?: (args: MasqStopArgs) => void | Promise<void>;
|
|
63
|
+
enabled?: boolean;
|
|
64
|
+
};
|
|
65
|
+
export type ResolvedMasqOptions = Required<Omit<MasqPluginOptions, 'onStart' | 'onStop' | 'startPath'>> & Pick<MasqPluginOptions, 'onStart' | 'onStop'> & {
|
|
66
|
+
startPath: string;
|
|
67
|
+
apiRoute: string;
|
|
68
|
+
adminRoute: string;
|
|
69
|
+
};
|
|
70
|
+
/** The signed state of an active masquerade (in an httpOnly cookie). */
|
|
71
|
+
export type MasqState = {
|
|
72
|
+
/** Masquerader id. */
|
|
73
|
+
by: string;
|
|
74
|
+
/** Target id. */
|
|
75
|
+
as: string;
|
|
76
|
+
/** Started (ISO). */
|
|
77
|
+
at: string;
|
|
78
|
+
/** Borrowed session ends (ISO). */
|
|
79
|
+
until: string;
|
|
80
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,81 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-masq",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
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
|
+
"homepage": "https://github.com/ExtantApe/payload-plugin-masq#readme",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/ExtantApe/payload-plugin-masq/issues"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [
|
|
10
|
+
"payload",
|
|
11
|
+
"payload-plugin",
|
|
12
|
+
"payloadcms",
|
|
13
|
+
"masquerade",
|
|
14
|
+
"impersonation",
|
|
15
|
+
"login-as",
|
|
16
|
+
"support"
|
|
17
|
+
],
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/ExtantApe/payload-plugin-masq.git"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./client": {
|
|
30
|
+
"types": "./dist/client/index.d.ts",
|
|
31
|
+
"import": "./dist/client/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./rsc": {
|
|
34
|
+
"types": "./dist/rsc/index.d.ts",
|
|
35
|
+
"import": "./dist/rsc/index.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"main": "./dist/index.js",
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"files": [
|
|
41
|
+
"dist",
|
|
42
|
+
"README.md",
|
|
43
|
+
"LICENSE"
|
|
44
|
+
],
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=20.9"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"prepack": "npm run build",
|
|
53
|
+
"prepublishOnly": "npm run typecheck && npm test"
|
|
54
|
+
},
|
|
55
|
+
"peerDependencies": {
|
|
56
|
+
"@payloadcms/next": "^3.80.0",
|
|
57
|
+
"@payloadcms/ui": "^3.80.0",
|
|
58
|
+
"next": ">=15",
|
|
59
|
+
"payload": "^3.80.0",
|
|
60
|
+
"react": ">=19"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@payloadcms/db-mongodb": "3.92.1",
|
|
64
|
+
"@payloadcms/next": "3.92.1",
|
|
65
|
+
"@payloadcms/ui": "3.92.1",
|
|
66
|
+
"@types/node": "^24.0.0",
|
|
67
|
+
"@types/react": "^19.3.0",
|
|
68
|
+
"@types/react-dom": "^19.3.0",
|
|
69
|
+
"graphql": "^16.14.2",
|
|
70
|
+
"mongodb-memory-server": "^11.3.0",
|
|
71
|
+
"next": "16.4.5",
|
|
72
|
+
"payload": "3.92.1",
|
|
73
|
+
"react": "^19.3.1",
|
|
74
|
+
"react-dom": "^19.3.1",
|
|
75
|
+
"typescript": "^5.9.0",
|
|
76
|
+
"vitest": "^5.1.0"
|
|
77
|
+
},
|
|
78
|
+
"overrides": {
|
|
79
|
+
"dompurify": "^3.4.17"
|
|
80
|
+
}
|
|
81
|
+
}
|