@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/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,177 @@
|
|
|
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 on a live site. 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
|
+
- **Checked on every request.** While a borrowed session is live, every request that carries
|
|
48
|
+
its token, in the cookie or an `Authorization` header, asks `canMasquerade` again with the
|
|
49
|
+
masquerader and the target loaded fresh, then your `recheck` if you set one. If the answer
|
|
50
|
+
is no (the masquerader was demoted or deleted, or the target changed so the rule refuses),
|
|
51
|
+
the borrowed session is deleted on that request, the request runs signed out, and `onStop`
|
|
52
|
+
gets `revoked: true`. If the check itself fails (a read or the delete throws), the borrowed
|
|
53
|
+
token is ignored for that request, so it runs signed out. The cost is two reads by ID on
|
|
54
|
+
requests that carry a borrowed token, and nothing on any other request.
|
|
55
|
+
- **Limits of the check.** It is an auth strategy that Masq puts first on its collection, so an
|
|
56
|
+
auth collection listed before it, or a strategy another plugin puts in front later, runs
|
|
57
|
+
before it. Signing the masquerader out everywhere doesn't end a borrowed session; if that
|
|
58
|
+
should end it, check it in `recheck`. `recheck` runs before anyone is signed in, so
|
|
59
|
+
`req.user` isn't set yet; use the `masquerader` and `target` it gets. The token is read from
|
|
60
|
+
the cookie even on cross-site requests, the same as Payload's own sign-in. Behind a Next.js
|
|
61
|
+
`basePath`, stopping a revoked masquerade can report `onStop` twice.
|
|
62
|
+
- Never as yourself, no nesting, no public endpoints: masquerading needs a signed-in user the
|
|
63
|
+
rules allow.
|
|
64
|
+
|
|
65
|
+
## Upgrading from 0.1.0
|
|
66
|
+
|
|
67
|
+
Required, once: before or right after upgrading, end every running masquerade. Borrowed
|
|
68
|
+
sessions started by 0.1.0 carry no mark, so with the masquerade cookie cleared they can still
|
|
69
|
+
write, and Payload keeps refreshing them. There is no sound way to tell them apart from normal
|
|
70
|
+
sessions afterwards. A borrowed session is stored on the **target's** account, so signing the
|
|
71
|
+
masquerader out isn't enough. The commands below clear **everyone's** sessions, so every user
|
|
72
|
+
is signed out once and signs in again. (Clearing only the masqueraded users' sessions would be
|
|
73
|
+
enough, but no command for that is given here because none has been tested.)
|
|
74
|
+
|
|
75
|
+
With the Local API (any database adapter; tested), for the default `users` collection:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
await payload.db.updateMany({ collection: 'users', where: {}, data: { sessions: [] } })
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Or on MongoDB from the command line (the same change, not tested here):
|
|
82
|
+
|
|
83
|
+
```sh
|
|
84
|
+
mongosh "$DATABASE_URI" --eval 'db.users.updateMany({}, { $set: { sessions: [] } })'
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
From 0.1.2, Masq needs `useSessions` left out or set to `true` on its auth collection, because it
|
|
88
|
+
ends a borrowed token by deleting its session. Any other value (`false`, `0`, an empty string)
|
|
89
|
+
stops the build. It checks again when Payload starts, so a plugin listed after Masq or a change
|
|
90
|
+
to the built config that turns sessions off stops start-up too. If sessions are off anyway, for
|
|
91
|
+
example when start-up checks were skipped, no borrowed token signs anyone in and no masquerade
|
|
92
|
+
can start. If you ran 0.1.0 or 0.1.1 that way, changing
|
|
93
|
+
`PAYLOAD_SECRET` is the only way to end the old tokens, and it signs everyone out.
|
|
94
|
+
|
|
95
|
+
## On its own, and with others
|
|
96
|
+
|
|
97
|
+
**On its own:** it needs an auth collection (default `users`) with sessions on, which is Payload's default, and your `canMasquerade`. It doesn't need any other plugin. Auditing is up to your `onStart` and `onStop`.
|
|
98
|
+
|
|
99
|
+
**Works with:**
|
|
100
|
+
- **Audit Trail:** call Audit Trail's `recordEvent` from `onStart` and `onStop` (with `masquerade` in its `actions`), and use `masqueraderOf(req)` in its `via` so a change made while masquerading says who really made it.
|
|
101
|
+
- **Hats:** as Hats' design describes, Hats' `blocked(req)` refuses switching while masquerading, and your `canMasquerade` refuses a switched session (`hatsStateOf(user).via`).
|
|
102
|
+
|
|
103
|
+
**Family:** It's part of the **Identity** family (a working draft): plugins designed to sit together for accounts and access.
|
|
104
|
+
|
|
105
|
+
## Install
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
npm install @extantape/payload-plugin-masq
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { masqPlugin } from '@extantape/payload-plugin-masq'
|
|
113
|
+
|
|
114
|
+
export default buildConfig({
|
|
115
|
+
plugins: [
|
|
116
|
+
masqPlugin({
|
|
117
|
+
// Required. Who may masquerade (target absent = may they use masquerade at all).
|
|
118
|
+
canMasquerade: ({ user, target }) => user.role === 'admin',
|
|
119
|
+
onStart: async ({ req, masquerader, target, reason }) => {
|
|
120
|
+
await req.payload.create({
|
|
121
|
+
collection: 'audit-log',
|
|
122
|
+
data: { action: 'masquerade-start', by: masquerader.id, user: target.id, reason },
|
|
123
|
+
req,
|
|
124
|
+
})
|
|
125
|
+
},
|
|
126
|
+
onStop: async ({ req, masqueraderId, targetId, expired, revoked }) => {
|
|
127
|
+
/* … */
|
|
128
|
+
},
|
|
129
|
+
}),
|
|
130
|
+
],
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Then run `payload generate:importmap`. Add the banner to your site layout (a Server
|
|
135
|
+
Component) so masqueraders see it outside the admin too:
|
|
136
|
+
|
|
137
|
+
```tsx
|
|
138
|
+
import { MasqueradeBanner } from '@extantape/payload-plugin-masq/rsc'
|
|
139
|
+
|
|
140
|
+
<MasqueradeBanner payload={payload} />
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## Options
|
|
144
|
+
|
|
145
|
+
| Option | Default | |
|
|
146
|
+
|---|---|---|
|
|
147
|
+
| `canMasquerade` | (required) | `({ payload, user, target? }) => boolean`. No default: nobody can masquerade until you decide. |
|
|
148
|
+
| `collection` | `'users'` | Auth collection. |
|
|
149
|
+
| `duration` | `3600` | Seconds the borrowed session lasts. |
|
|
150
|
+
| `readOnly` | `true` | Refuse create, update and delete while masquerading. |
|
|
151
|
+
| `requireReason` | `false` | Ask for a reason; passed to `onStart`. |
|
|
152
|
+
| `labelField` | `'email'` | Name shown in the search and banner. |
|
|
153
|
+
| `searchFields` | `['email']` | Fields the search matches. |
|
|
154
|
+
| `startPath` | admin route | Where to go after starting. |
|
|
155
|
+
| `adminBanner` | `true` | Banner in the admin header. |
|
|
156
|
+
| `adminView` | `true` | Masquerade area and nav link. |
|
|
157
|
+
| `listColumn` | `true` | Masquerade column in the users list (added to `defaultColumns`). |
|
|
158
|
+
| `recheck` | | `({ payload, req, masquerader, target }) => boolean`, asked on every request a borrowed session makes, after `canMasquerade`. Only exactly `true` keeps the session; anything else, or a throw, ends it. Use it for checks `canMasquerade` doesn't make, such as a deny list. `req.user` isn't set yet. |
|
|
159
|
+
| `onStart`, `onStop` | | Audit hooks. `onStop` gets `revoked: true` when the per-request check ended the session. |
|
|
160
|
+
| `enabled` | `true` | |
|
|
161
|
+
|
|
162
|
+
## Endpoints
|
|
163
|
+
|
|
164
|
+
On the auth collection (`/api/users/…`): `POST /:id/masq` (start, body `{ reason? }`),
|
|
165
|
+
`POST /masq/stop` (return) and `GET /masq/search?q=` (admin search). All need a signed-in
|
|
166
|
+
user that `canMasquerade` allows.
|
|
167
|
+
|
|
168
|
+
## Acknowledgements
|
|
169
|
+
|
|
170
|
+
[payload-plugin-masquerade](https://github.com/manutepowa/payload-plugin-masquerade) came first
|
|
171
|
+
and is worth a look. We built this one because our direction differed in ways too large to
|
|
172
|
+
merge: a short borrowed session that ends on return, restore only for a still-valid masquerader,
|
|
173
|
+
an access-checked admin-only search, a banner on the site as well as the admin, and audit hooks.
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
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,159 @@
|
|
|
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, sessionsOn, 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
|
+
// Without sessions a borrowed token can't be ended early, so none is handed out.
|
|
28
|
+
if (!sessionsOn(req.payload, opts.collection))
|
|
29
|
+
throw new APIError('Masquerade needs sessions turned on.', 500, undefined, true);
|
|
30
|
+
if (isMasquerading(req.payload, req.headers))
|
|
31
|
+
throw new APIError('Stop masquerading first.', 400, undefined, true);
|
|
32
|
+
const own = parseCookies(req.headers).get(tokenCookie(req));
|
|
33
|
+
if (!own)
|
|
34
|
+
throw new APIError('Masquerade needs a browser sign-in.', 400, undefined, true);
|
|
35
|
+
const id = String(req.routeParams?.id ?? '');
|
|
36
|
+
if (!id || id === String(user.id))
|
|
37
|
+
throw new APIError('Choose another user.', 400, undefined, true);
|
|
38
|
+
await addDataAndFileToRequest(req);
|
|
39
|
+
const reason = typeof req.data?.reason === 'string' ? req.data.reason.trim().slice(0, 500) || null : null;
|
|
40
|
+
if (opts.requireReason && !reason)
|
|
41
|
+
throw new APIError('Say why you are masquerading.', 400, undefined, true);
|
|
42
|
+
const target = (await req.payload.findByID({
|
|
43
|
+
collection: opts.collection,
|
|
44
|
+
id,
|
|
45
|
+
depth: 0,
|
|
46
|
+
overrideAccess: true,
|
|
47
|
+
showHiddenFields: true,
|
|
48
|
+
disableErrors: true,
|
|
49
|
+
req,
|
|
50
|
+
}));
|
|
51
|
+
if (!target)
|
|
52
|
+
throw new APIError('User not found.', 404, undefined, true);
|
|
53
|
+
if (!(await mayMasquerade(opts, { payload: req.payload, user, target })))
|
|
54
|
+
throw new APIError('You may not masquerade as this user.', 403, undefined, true);
|
|
55
|
+
const collectionConfig = req.payload.collections[opts.collection].config;
|
|
56
|
+
const { sid } = await addSessionToUser({ collectionConfig, payload: req.payload, req, user: target });
|
|
57
|
+
const { token } = await jwtSign({
|
|
58
|
+
// Marked as borrowed, so it stays read-only and can't be refreshed even without the state cookie.
|
|
59
|
+
fieldsToSign: { ...getFieldsToSign({ collectionConfig, email: String(target.email ?? ''), sid, user: target }), [BORROWED_CLAIM]: String(user.id) },
|
|
60
|
+
secret: req.payload.secret,
|
|
61
|
+
tokenExpiration: opts.duration,
|
|
62
|
+
});
|
|
63
|
+
const now = Date.now();
|
|
64
|
+
const state = { by: String(user.id), as: id, at: new Date(now).toISOString(), until: new Date(now + opts.duration * 1000).toISOString() };
|
|
65
|
+
await opts.onStart?.({ req, masquerader: user, target, reason });
|
|
66
|
+
return json({ ok: true, redirect: opts.startPath }, [
|
|
67
|
+
cookie(req.payload, opts.collection, tokenCookie(req), token, opts.duration),
|
|
68
|
+
// The masquerader's own token goes back only to the stop endpoint.
|
|
69
|
+
cookie(req.payload, opts.collection, RETURN_COOKIE, own, STATE_SECONDS, `${opts.apiRoute}/${opts.collection}/masq/stop`),
|
|
70
|
+
cookie(req.payload, opts.collection, STATE_COOKIE, encodeState(req.payload.secret, state), STATE_SECONDS),
|
|
71
|
+
]);
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
/** POST /api/<collection>/masq/stop: end the borrowed session and restore the masquerader's own. */
|
|
75
|
+
export const stopEndpoint = {
|
|
76
|
+
path: '/masq/stop',
|
|
77
|
+
method: 'post',
|
|
78
|
+
handler: async (req) => {
|
|
79
|
+
const opts = masqOptions(req.payload);
|
|
80
|
+
const state = masqStateOf(req.payload, req.headers);
|
|
81
|
+
// Our own writes (and onStop's) are allowed even in read-only mode.
|
|
82
|
+
req.context = { ...req.context, masqInternal: true };
|
|
83
|
+
const own = parseCookies(req.headers).get(RETURN_COOKIE);
|
|
84
|
+
const stopPath = `${opts.apiRoute}/${opts.collection}/masq/stop`;
|
|
85
|
+
const clear = [cookie(req.payload, opts.collection, RETURN_COOKIE, '', -1, stopPath), cookie(req.payload, opts.collection, STATE_COOKIE, '', -1)];
|
|
86
|
+
// End the borrowed session if it is still alive: named by the state cookie, or, if that
|
|
87
|
+
// cookie is gone, by the borrowed token's own claim.
|
|
88
|
+
const borrowed = req.user;
|
|
89
|
+
// Only a genuine claim, on the token that signs in the very user this request is authenticated as.
|
|
90
|
+
const claim = borrowed ? borrowedClaim(req.payload, req.headers, { userId: String(borrowed.id), sid: borrowed._sid }) : null;
|
|
91
|
+
const claimedBy = claim && borrowed && claim.id === String(borrowed.id) ? claim.by : null;
|
|
92
|
+
// With the state cookie, only the borrowed session it names: same target and same masquerader.
|
|
93
|
+
const live = Boolean(borrowed?.collection === opts.collection && claimedBy && (!state || (claim.id === state.as && claimedBy === state.by)));
|
|
94
|
+
if (live && borrowed?._sid) {
|
|
95
|
+
const doc = (await req.payload.findByID({ collection: opts.collection, id: borrowed.id, depth: 0, overrideAccess: true, showHiddenFields: true, req }));
|
|
96
|
+
await req.payload.db.updateOne({
|
|
97
|
+
collection: opts.collection,
|
|
98
|
+
id: borrowed.id,
|
|
99
|
+
data: { sessions: (doc.sessions ?? []).filter((s) => s.id !== borrowed._sid) },
|
|
100
|
+
req,
|
|
101
|
+
returning: false,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
// Restore only a still-valid token of the same masquerader who may still masquerade.
|
|
105
|
+
const restored = state && own ? await req.payload.auth({ headers: new Headers({ Authorization: `JWT ${own}` }) }).catch(() => null) : null;
|
|
106
|
+
const user = (restored?.user ?? null);
|
|
107
|
+
const ok = Boolean(state && user && String(user.id) === state.by && (await mayMasquerade(opts, { payload: req.payload, user: user })));
|
|
108
|
+
if (state)
|
|
109
|
+
await opts.onStop?.({ req, masqueraderId: state.by, targetId: state.as, expired: !live, restored: ok });
|
|
110
|
+
else if (live && claimedBy)
|
|
111
|
+
await opts.onStop?.({ req, masqueraderId: claimedBy, targetId: String(borrowed.id), expired: false, restored: false });
|
|
112
|
+
if (!ok)
|
|
113
|
+
return json({ ok: true, restored: false, redirect: `${opts.adminRoute}/login` }, [...clear, cookie(req.payload, opts.collection, tokenCookie(req), '', -1)]);
|
|
114
|
+
const seconds = req.payload.collections[opts.collection].config.auth.tokenExpiration;
|
|
115
|
+
return json({ ok: true, restored: true, redirect: `${opts.adminRoute}/collections/${opts.collection}/${state.as}` }, [
|
|
116
|
+
...clear,
|
|
117
|
+
cookie(req.payload, opts.collection, tokenCookie(req), own, seconds),
|
|
118
|
+
]);
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* GET /api/<collection>/masq/search?q=&page=: the admin user search. Only for
|
|
123
|
+
* people allowed to masquerade at all, and it reads with their own access, so it
|
|
124
|
+
* never shows a user they could not already see. Lists only users they may
|
|
125
|
+
* masquerade as.
|
|
126
|
+
*/
|
|
127
|
+
export const searchEndpoint = {
|
|
128
|
+
path: '/masq/search',
|
|
129
|
+
method: 'get',
|
|
130
|
+
handler: async (req) => {
|
|
131
|
+
const opts = masqOptions(req.payload);
|
|
132
|
+
const user = signedIn(req);
|
|
133
|
+
if (!(await mayMasquerade(opts, { payload: req.payload, user })))
|
|
134
|
+
throw new APIError('Not allowed.', 403, undefined, true);
|
|
135
|
+
const q = String(req.searchParams?.get('q') ?? '').trim().slice(0, 100);
|
|
136
|
+
const page = Math.max(1, Number(req.searchParams?.get('page')) || 1);
|
|
137
|
+
const where = {
|
|
138
|
+
and: [{ id: { not_equals: user.id } }, ...(q ? [{ or: opts.searchFields.map((f) => ({ [f]: { like: q } })) }] : [])],
|
|
139
|
+
};
|
|
140
|
+
const found = await req.payload.find({
|
|
141
|
+
collection: opts.collection,
|
|
142
|
+
where,
|
|
143
|
+
page,
|
|
144
|
+
limit: 20,
|
|
145
|
+
depth: 0,
|
|
146
|
+
sort: opts.labelField,
|
|
147
|
+
overrideAccess: false,
|
|
148
|
+
user: req.user,
|
|
149
|
+
req,
|
|
150
|
+
});
|
|
151
|
+
const docs = await Promise.all(found.docs.map(async (d) => ({
|
|
152
|
+
id: String(d.id),
|
|
153
|
+
label: String(d[opts.labelField] ?? d.email ?? d.id),
|
|
154
|
+
email: d.email ?? null,
|
|
155
|
+
allowed: await mayMasquerade(opts, { payload: req.payload, user, target: d }),
|
|
156
|
+
})));
|
|
157
|
+
return json({ docs, page: found.page, totalPages: found.totalPages, totalDocs: found.totalDocs });
|
|
158
|
+
},
|
|
159
|
+
};
|
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, MasqRecheckArgs, 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;
|