@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/dist/state.js ADDED
@@ -0,0 +1,154 @@
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
+ * Every value the request carries for the cookie `name`, read at least as loosely as Payload's own JWT strategy
35
+ * reads it: names trimmed, every occurrence kept (Payload keeps the last), each value both as sent and URI-decoded.
36
+ */
37
+ function cookieValues(headers, name) {
38
+ const out = [];
39
+ for (const part of (headers.get('Cookie') ?? '').split(';')) {
40
+ const [key, ...rest] = part.split('=');
41
+ if (key?.trim() !== name)
42
+ continue;
43
+ const raw = rest.join('=');
44
+ out.push(raw);
45
+ try {
46
+ const decoded = decodeURI(raw);
47
+ if (decoded !== raw)
48
+ out.push(decoded);
49
+ }
50
+ catch {
51
+ // Payload skips a value it can't decode; the raw value is still checked.
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+ /** Base64url decoded the way jose decodes it (Node's decoder, which skips whitespace, padding and other stray characters). */
57
+ const b64 = (s) => Buffer.from(s, 'base64url');
58
+ /**
59
+ * Every genuine borrowed claim in the request, cookie first, then the Authorization header. It reads tokens at
60
+ * least as loosely as Payload's JWT strategy and jose do (padding or whitespace in the signature, spaces around
61
+ * the cookie name, any letter case in the scheme), so no spelling Payload signs in with escapes the checks.
62
+ */
63
+ export function borrowedClaims(payload, headers) {
64
+ if (!headers || !payload.secret)
65
+ return [];
66
+ const auth = headers.get('Authorization') ?? '';
67
+ const scheme = /^\s*(?:jwt|bearer)\s+/i.exec(auth);
68
+ const tokens = [
69
+ ...cookieValues(headers, `${payload.config?.cookiePrefix ?? 'payload'}-token`).map((t) => [t, 'cookie']),
70
+ ...(scheme ? [[auth.slice(scheme[0].length), 'header']] : []),
71
+ ];
72
+ const out = [];
73
+ const seen = new Set();
74
+ for (const [token, from] of tokens) {
75
+ const [head, body, sig] = token.split('.');
76
+ if (!head || !body || !sig)
77
+ continue;
78
+ // The same signed token repeated (or its raw and decoded copies) counts once.
79
+ const key = `${from} ${head}.${body}`;
80
+ if (seen.has(key))
81
+ continue;
82
+ const expected = crypto.createHmac('sha256', payload.secret).update(`${head}.${body}`).digest();
83
+ const given = b64(sig);
84
+ if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given))
85
+ continue;
86
+ seen.add(key);
87
+ try {
88
+ if (JSON.parse(b64(head).toString('utf8')).alg !== 'HS256')
89
+ continue;
90
+ const claims = JSON.parse(b64(body).toString('utf8'));
91
+ const by = claims[BORROWED_CLAIM];
92
+ if (typeof by === 'string' && by)
93
+ out.push({
94
+ by,
95
+ id: String(claims.id ?? ''),
96
+ sid: typeof claims.sid === 'string' ? claims.sid : null,
97
+ exp: typeof claims.exp === 'number' ? claims.exp : null,
98
+ token,
99
+ from,
100
+ });
101
+ }
102
+ catch {
103
+ // Not a JWT we can read: not a borrowed session.
104
+ }
105
+ }
106
+ return out;
107
+ }
108
+ /**
109
+ * The first borrowed claim, or with `session`, the claim on the very token that signed in: the same user and the
110
+ * same session id. A second token for the same user (another masquerader's, or the user's own) is never picked.
111
+ */
112
+ export function borrowedClaim(payload, headers, session) {
113
+ const all = borrowedClaims(payload, headers);
114
+ const c = session === undefined ? all[0] : session.sid ? all.find((x) => x.id === session.userId && x.sid === session.sid) : undefined;
115
+ return c ? { by: c.by, id: c.id } : null;
116
+ }
117
+ /**
118
+ * Whether the masquerade collection, as Payload finally built it, keeps sessions. Payload turns sessions off for
119
+ * any falsy useSessions, and another plugin or the host can change it after masq has run, so this reads the
120
+ * built config and only exactly true counts.
121
+ */
122
+ export const sessionsOn = (payload, collection) => payload.collections?.[collection]?.config?.auth?.useSessions === true;
123
+ /** The masquerader's id if the request carries a genuine borrowed session's token. */
124
+ export const borrowedBy = (payload, headers) => borrowedClaim(payload, headers)?.by ?? null;
125
+ /**
126
+ * Whether the request is masquerading: it carries the signed state cookie, or a
127
+ * borrowed session's token (so dropping the state cookie doesn't lift read-only).
128
+ */
129
+ export const isMasquerading = (payload, headers) => Boolean(masqStateOf(payload, headers) || borrowedBy(payload, headers));
130
+ /** The masquerader's id for a request, for audit trails: `masqueraderOf(req)`. */
131
+ export const masqueraderOf = (req) => masqStateOf(req.payload, req.headers)?.by ?? null;
132
+ export const masqOptions = (payload) => payload.config.custom?.masq;
133
+ export function cookie(payload, slug, name, value, seconds, path = '/') {
134
+ const auth = payload.collections[slug].config.auth;
135
+ return generateCookie({
136
+ name,
137
+ value,
138
+ path,
139
+ httpOnly: true,
140
+ secure: auth.cookies.secure,
141
+ sameSite: 'Lax',
142
+ domain: auth.cookies.domain ?? undefined,
143
+ expires: new Date(Date.now() + seconds * 1000),
144
+ returnCookieAsObject: false,
145
+ });
146
+ }
147
+ /**
148
+ * For your own server actions and route handlers that write through the Local
149
+ * API without the request: refuse while masquerading (read-only masquerade).
150
+ */
151
+ export function assertNotMasquerading(payload, headers) {
152
+ if (payload.config.custom?.masq?.readOnly !== false && isMasquerading(payload, headers))
153
+ throw new Error('Masquerade is read-only: nothing can be created, changed or deleted while masquerading.');
154
+ }
@@ -0,0 +1,98 @@
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
+ * The plugin ended the borrowed session itself, because a recheck said no: `canMasquerade`
30
+ * (or `recheck`) no longer answered exactly `true`, or either account is gone.
31
+ */
32
+ revoked?: boolean;
33
+ };
34
+ export type MasqRecheckArgs = {
35
+ payload: Payload;
36
+ req?: PayloadRequest;
37
+ masquerader: MasqUser;
38
+ target: MasqUser;
39
+ };
40
+ export type MasqPluginOptions = {
41
+ /** Auth collection to masquerade in. Default `users`. */
42
+ collection?: string;
43
+ /**
44
+ * Who may masquerade, and as whom. Required: there is no default, so nobody
45
+ * can masquerade until you decide. Masquerading as oneself and nesting are
46
+ * always refused.
47
+ */
48
+ canMasquerade: (args: MasqPermissionArgs) => boolean | Promise<boolean>;
49
+ /** Length of the borrowed session in seconds. Default 3600 (one hour). */
50
+ duration?: number;
51
+ /**
52
+ * Look, don't touch: refuse create, update and delete while masquerading, everywhere
53
+ * Payload runs (REST, GraphQL, admin, Local API with the request). Payload's own
54
+ * bookkeeping (preferences, document locks) still works so the admin behaves normally.
55
+ * Default true. For your own server actions, call `assertNotMasquerading(payload, headers)`.
56
+ */
57
+ readOnly?: boolean;
58
+ /** Ask for a reason before starting; it is passed to `onStart`. Default false. */
59
+ requireReason?: boolean;
60
+ /** Field shown as each user's name in the search. Default `email`. */
61
+ labelField?: string;
62
+ /** Fields the admin search matches (`like`). Default `['email']`. */
63
+ searchFields?: string[];
64
+ /** Where to go after starting. Default: the admin dashboard. */
65
+ startPath?: string;
66
+ /** Add the banner to the admin header. Default true. */
67
+ adminBanner?: boolean;
68
+ /** Show a Masquerade column (button per row) in the users list by default. Default true. */
69
+ listColumn?: boolean;
70
+ /** Add the "Masquerade" view (admin-only user search) and its nav link. Default true. */
71
+ adminView?: boolean;
72
+ /**
73
+ * An extra check run with `canMasquerade` on every request a borrowed session makes. Only an
74
+ * answer of exactly `true` keeps the session; anything else, a thrown error included, ends it.
75
+ * Use it for rules that don't belong in `canMasquerade`, such as a deny list. Keep it cheap:
76
+ * it runs once per request while masquerading.
77
+ */
78
+ recheck?: (args: MasqRecheckArgs) => unknown;
79
+ onStart?: (args: MasqStartArgs) => void | Promise<void>;
80
+ onStop?: (args: MasqStopArgs) => void | Promise<void>;
81
+ enabled?: boolean;
82
+ };
83
+ export type ResolvedMasqOptions = Required<Omit<MasqPluginOptions, 'onStart' | 'onStop' | 'startPath' | 'recheck'>> & Pick<MasqPluginOptions, 'onStart' | 'onStop' | 'recheck'> & {
84
+ startPath: string;
85
+ apiRoute: string;
86
+ adminRoute: string;
87
+ };
88
+ /** The signed state of an active masquerade (in an httpOnly cookie). */
89
+ export type MasqState = {
90
+ /** Masquerader id. */
91
+ by: string;
92
+ /** Target id. */
93
+ as: string;
94
+ /** Started (ISO). */
95
+ at: string;
96
+ /** Borrowed session ends (ISO). */
97
+ until: string;
98
+ };
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.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
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
+ }