@payloadcms/figma 1.0.0-beta.1 → 1.0.0-beta.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.
Files changed (45) hide show
  1. package/dist/adapters/build-lambda-zip.d.ts +2 -1
  2. package/dist/adapters/build-lambda-zip.js +4 -1
  3. package/dist/adapters/deploy-output/assertDeployableServerActionsKey.d.ts +14 -0
  4. package/dist/adapters/deploy-output/assertDeployableServerActionsKey.js +33 -0
  5. package/dist/commands/upload-schema.js +23 -9
  6. package/dist/db-content-api/generated/content-api-types.d.ts +247 -0
  7. package/dist/db-content-api/index.js +40 -3
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +1 -0
  10. package/dist/oauth/defaults.js +2 -2
  11. package/dist/oauth/hooks/me.d.ts +4 -3
  12. package/dist/oauth/hooks/me.js +6 -52
  13. package/dist/oauth/hooks/refresh.js +9 -1
  14. package/dist/oauth/index.js +1 -1
  15. package/dist/oauth/strategy/index.d.ts +3 -0
  16. package/dist/oauth/strategy/index.js +49 -3
  17. package/dist/oauth/utilities/clearCookie.d.ts +1 -0
  18. package/dist/oauth/utilities/clearCookie.js +13 -9
  19. package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
  20. package/dist/oauth/utilities/clearSessionCookies.js +17 -0
  21. package/dist/oauth/utilities/getAuthorizeURL.js +1 -2
  22. package/dist/oauth/utilities/mergeHeaders.js +11 -23
  23. package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
  24. package/dist/oauth/utilities/refreshTokens.js +45 -34
  25. package/dist/plugin/build-config.js +10 -7
  26. package/dist/plugin/dev-cookie-names.d.ts +4 -1
  27. package/dist/plugin/dev-cookie-names.js +6 -3
  28. package/dist/plugin/environment-error.d.ts +4 -0
  29. package/dist/plugin/environment-error.js +22 -0
  30. package/dist/plugin/mcp-oauth.d.ts +10 -0
  31. package/dist/plugin/mcp-oauth.js +24 -0
  32. package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
  33. package/dist/plugin/sandbox-upload-fetch.js +22 -14
  34. package/dist/scss.d.js +1 -1
  35. package/dist/storage-content-api/api-types.d.ts +22 -1
  36. package/dist/storage-content-api/api-types.js +2 -1
  37. package/dist/storage-content-api/client.d.ts +3 -3
  38. package/dist/storage-content-api/client.js +13 -35
  39. package/dist/storage-content-api/index.js +20 -21
  40. package/dist/storage-content-api/staticHandler.js +4 -1
  41. package/dist/storage-content-api/types.d.ts +2 -2
  42. package/dist/utils/env-management.js +7 -0
  43. package/package.json +20 -22
  44. package/dist/db-content-api/utilities/auth.d.ts +0 -29
  45. package/dist/db-content-api/utilities/auth.js +0 -82
@@ -2,11 +2,13 @@ import * as jose from 'jose';
2
2
  import { APIError, parseCookies } from 'payload';
3
3
  import { JWTValidationError, validatePayloadAdminToken } from '../../auth/jwt-validator.js';
4
4
  import { getInfraEnvironment } from '../../constants.js';
5
+ import { clearSessionCookies } from '../utilities/clearSessionCookies.js';
5
6
  import { createDebugLogger } from '../utilities/createDebugLogger.js';
6
7
  import { getTokenExp } from '../utilities/getTokenExp.js';
7
8
  import { mergeHeaders } from '../utilities/mergeHeaders.js';
8
9
  import { refreshTokens } from '../utilities/refreshTokens.js';
9
10
  export class Strategy {
11
+ /** Keeps /me aligned with authentication-time renewal without changing request cookies. */ authenticatedTokenExpirations = new WeakMap();
10
12
  clientID;
11
13
  collection;
12
14
  collectionOptions;
@@ -38,6 +40,11 @@ export class Strategy {
38
40
  // Prevent wokiness with `this`
39
41
  this.ensureMeta = this.ensureMeta.bind(this);
40
42
  }
43
+ setTokenExpiration({ exp, headers, verifyResult }) {
44
+ if (verifyResult.user) {
45
+ this.authenticatedTokenExpirations.set(headers, exp);
46
+ }
47
+ }
41
48
  async authenticate({ canSetHeaders, headers, payload }) {
42
49
  const debugLogger = createDebugLogger(payload, this.debug);
43
50
  await this.ensureMeta();
@@ -69,11 +76,13 @@ export class Strategy {
69
76
  msg: 'No access token found, but refresh token exists. Attempting to refresh...'
70
77
  });
71
78
  const refreshed = await refreshTokens({
79
+ headers,
72
80
  payload,
73
81
  refreshToken,
74
82
  strategy: this
75
83
  });
76
- if (refreshed) {
84
+ if (refreshed.status === 'success') {
85
+ const tokenExpiration = refreshed.decodedOauthToken.exp;
77
86
  const verifyResult = await this.verify({
78
87
  headers,
79
88
  payload,
@@ -83,6 +92,11 @@ export class Strategy {
83
92
  msg: 'Token refreshed. Verifying...',
84
93
  verifyResult
85
94
  });
95
+ this.setTokenExpiration({
96
+ exp: tokenExpiration,
97
+ headers,
98
+ verifyResult
99
+ });
86
100
  // Only return response headers (to set cookies) when canSetHeaders is true.
87
101
  // During RSC navigation, canSetHeaders=false because response streaming
88
102
  // has already started and cookies cannot be modified.
@@ -100,6 +114,15 @@ export class Strategy {
100
114
  user: verifyResult.user
101
115
  };
102
116
  } else {
117
+ if (refreshed.status === 'rejected' && canSetHeaders) {
118
+ return {
119
+ responseHeaders: clearSessionCookies({
120
+ headers,
121
+ strategy: this
122
+ }),
123
+ user: null
124
+ };
125
+ }
103
126
  debugLogger.info({
104
127
  msg: 'Token refresh failed'
105
128
  });
@@ -126,6 +149,7 @@ export class Strategy {
126
149
  // but first set exp from refresh token
127
150
  // because access exp is likely very short lived
128
151
  if (typeof oauthTokenVerifyResult === 'object' && !(oauthTokenVerifyResult instanceof Error)) {
152
+ const tokenExpiration = oauthTokenVerifyResult.exp;
129
153
  if (refreshToken) {
130
154
  const refreshTokenExp = getTokenExp({
131
155
  debugLogger,
@@ -135,11 +159,17 @@ export class Strategy {
135
159
  oauthTokenVerifyResult.exp = refreshTokenExp;
136
160
  }
137
161
  }
138
- return this.verify({
162
+ const verifyResult = await this.verify({
139
163
  headers,
140
164
  payload,
141
165
  token: oauthTokenVerifyResult
142
166
  });
167
+ this.setTokenExpiration({
168
+ exp: tokenExpiration,
169
+ headers,
170
+ verifyResult
171
+ });
172
+ return verifyResult;
143
173
  }
144
174
  }
145
175
  // Handle expired access token with valid refresh token.
@@ -147,6 +177,7 @@ export class Strategy {
147
177
  // but only update cookies when canSetHeaders=true.
148
178
  if (oauthTokenVerifyResult instanceof JWTValidationError && oauthTokenVerifyResult.code === 'EXPIRED' && refreshToken && !this.collectionOptions.usePayloadJWT) {
149
179
  const refreshed = await refreshTokens({
180
+ headers,
150
181
  payload,
151
182
  refreshToken,
152
183
  strategy: this
@@ -154,7 +185,8 @@ export class Strategy {
154
185
  debugLogger.info({
155
186
  msg: 'Token expired. Refreshing...'
156
187
  });
157
- if (refreshed) {
188
+ if (refreshed.status === 'success') {
189
+ const tokenExpiration = refreshed.decodedOauthToken.exp;
158
190
  const verifyResult = await this.verify({
159
191
  headers,
160
192
  payload,
@@ -164,6 +196,11 @@ export class Strategy {
164
196
  msg: 'Token refreshed. Verifying...',
165
197
  verifyResult
166
198
  });
199
+ this.setTokenExpiration({
200
+ exp: tokenExpiration,
201
+ headers,
202
+ verifyResult
203
+ });
167
204
  if (canSetHeaders) {
168
205
  if (verifyResult.responseHeaders) {
169
206
  mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
@@ -178,6 +215,15 @@ export class Strategy {
178
215
  user: verifyResult.user
179
216
  };
180
217
  } else {
218
+ if (refreshed.status === 'rejected' && canSetHeaders) {
219
+ return {
220
+ responseHeaders: clearSessionCookies({
221
+ headers,
222
+ strategy: this
223
+ }),
224
+ user: null
225
+ };
226
+ }
181
227
  debugLogger.info({
182
228
  msg: 'Token refresh failed'
183
229
  });
@@ -6,3 +6,4 @@ export declare const clearCookie: (args: {
6
6
  overrides?: Partial<CookieOptions>;
7
7
  req: PayloadRequest;
8
8
  }) => void;
9
+ export declare const generateClearedCookie: (cookieName: string, cookieOptions: CookieOptions) => string;
@@ -1,23 +1,27 @@
1
1
  import { generateCookie } from 'payload';
2
- import { getCookieExpiration } from './getCookieExpiration.js';
3
2
  import { withPartitionedCookie } from './withPartitionedCookie.js';
4
3
  export const clearCookie = (args)=>{
5
4
  const options = {
6
5
  ...args.cookieOptions,
7
6
  ...args.overrides || {}
8
7
  };
9
- const clearedCookie = generateCookie({
10
- ...options,
11
- name: args.cookieName,
12
- expires: getCookieExpiration(options?.expires) ?? new Date(),
13
- returnCookieAsObject: false,
14
- value: ''
15
- });
8
+ const clearedCookie = generateClearedCookie(args.cookieName, options);
16
9
  if (!args.req.responseHeaders) {
17
10
  args.req.responseHeaders = new Headers();
18
11
  }
19
12
  // Match the Partitioned attribute the cookie was set with — a Max-Age=0 clear
20
13
  // without it targets the unpartitioned jar and won't delete the partitioned
21
14
  // cookie, so logout wouldn't clear the session in the cross-site Make iframe.
22
- args.req.responseHeaders.append('Set-Cookie', withPartitionedCookie(clearedCookie));
15
+ args.req.responseHeaders.append('Set-Cookie', clearedCookie);
16
+ };
17
+ export const generateClearedCookie = (cookieName, cookieOptions)=>{
18
+ const cookie = generateCookie({
19
+ ...cookieOptions,
20
+ name: cookieName,
21
+ expires: new Date(0),
22
+ maxAge: 0,
23
+ returnCookieAsObject: false,
24
+ value: ''
25
+ });
26
+ return withPartitionedCookie(cookie);
23
27
  };
@@ -0,0 +1,5 @@
1
+ import type { Strategy } from '../strategy/index.js';
2
+ export declare const clearSessionCookies: ({ headers, strategy, }: {
3
+ headers: Headers;
4
+ strategy: Strategy;
5
+ }) => Headers;
@@ -0,0 +1,17 @@
1
+ import { generateClearedCookie } from './clearCookie.js';
2
+ import { createCookieOptions } from './createCookieOptions.js';
3
+ export const clearSessionCookies = ({ headers, strategy })=>{
4
+ const cookieOptions = createCookieOptions({
5
+ collection: strategy.collection,
6
+ headers,
7
+ pluginOptions: strategy.pluginOptions
8
+ });
9
+ const responseHeaders = new Headers();
10
+ for (const name of [
11
+ strategy.cookieName,
12
+ `${strategy.cookieName}-refresh`
13
+ ]){
14
+ responseHeaders.append('Set-Cookie', generateClearedCookie(name, cookieOptions));
15
+ }
16
+ return responseHeaders;
17
+ };
@@ -1,6 +1,5 @@
1
1
  import crypto from 'crypto';
2
2
  import * as QueryString from 'qs-esm';
3
- import { v4 as uuid } from 'uuid';
4
3
  import { defaultScope } from '../defaults.js';
5
4
  export const getOAuthCallbackPath = ({ collection, endpointSlug })=>`/${collection.slug}/${endpointSlug}/login`;
6
5
  export const getAuthorizeURL = async ({ collection, collectionOptions, endpointSlug, existingCsrfNonce, failedRedirect, payload, pluginOptions, redirect, serverURLOverride, strategy })=>{
@@ -39,7 +38,7 @@ export const getAuthorizeURL = async ({ collection, collectionOptions, endpointS
39
38
  client_id: collectionOptions.clientID,
40
39
  code_challenge,
41
40
  code_challenge_method: 'S256',
42
- nonce: uuid(),
41
+ nonce: crypto.randomUUID(),
43
42
  redirect_uri: loginRedirectURL,
44
43
  response_mode: 'form_post',
45
44
  response_type: 'id_token%20token%20code',
@@ -1,35 +1,23 @@
1
1
  const headersToJoin = [
2
- 'set-cookie',
3
2
  'warning',
4
3
  'www-authenticate',
5
4
  'proxy-authenticate',
6
5
  'vary'
7
6
  ];
8
7
  export function mergeHeaders(sourceHeaders, destinationHeaders) {
9
- // Create a map to store combined headers
10
- const combinedHeaders = new Headers();
11
- // Add existing destination headers to the combined map
12
- destinationHeaders.forEach((value, key)=>{
13
- combinedHeaders.set(key, value);
14
- });
15
- // Add source headers to the combined map, joining specific headers
16
8
  sourceHeaders.forEach((value, key)=>{
17
- const lowerKey = key.toLowerCase();
18
- if (headersToJoin.includes(lowerKey)) {
19
- if (combinedHeaders.has(key)) {
20
- combinedHeaders.set(key, `${combinedHeaders.get(key)}, ${value}`);
21
- } else {
22
- combinedHeaders.set(key, value);
23
- }
9
+ if (key.toLowerCase() === 'set-cookie') {
10
+ return;
11
+ }
12
+ if (headersToJoin.includes(key.toLowerCase())) {
13
+ destinationHeaders.append(key, value);
24
14
  } else {
25
- combinedHeaders.set(key, value);
15
+ destinationHeaders.set(key, value);
26
16
  }
27
17
  });
28
- // Clear the destination headers and set the combined headers
29
- destinationHeaders.forEach((_, key)=>{
30
- destinationHeaders.delete(key);
31
- });
32
- combinedHeaders.forEach((value, key)=>{
33
- destinationHeaders.append(key, value);
34
- });
18
+ // Set-Cookie cannot be comma-joined: Expires contains commas, and each
19
+ // cookie must remain a separate header for browsers to apply both deletions.
20
+ for (const cookie of sourceHeaders.getSetCookie()){
21
+ destinationHeaders.append('Set-Cookie', cookie);
22
+ }
35
23
  }
@@ -2,14 +2,20 @@ import type jwt from 'jsonwebtoken';
2
2
  import type { Payload } from 'payload';
3
3
  import type { Strategy } from '../strategy/index.js';
4
4
  interface Args {
5
+ headers: Headers;
5
6
  payload: Payload;
6
7
  refreshToken: string;
7
8
  strategy: Strategy;
8
9
  }
9
- type Result = {
10
+ export type RefreshResult = {
10
11
  decodedOauthToken: jwt.JwtPayload;
11
12
  headers: Headers;
13
+ status: 'success';
12
14
  token: string;
13
- } | false;
14
- export declare const refreshTokens: ({ payload, refreshToken, strategy }: Args) => Promise<Result>;
15
+ } | {
16
+ status: 'rejected';
17
+ } | {
18
+ status: 'temporary_failure';
19
+ };
20
+ export declare const refreshTokens: ({ headers: requestHeaders, payload, refreshToken, strategy, }: Args) => Promise<RefreshResult>;
15
21
  export {};
@@ -1,20 +1,19 @@
1
1
  import { generateCookie } from 'payload';
2
- import { getPayloadAdminToken } from '../../api/figma-api.js';
2
+ import { FigmaApiError, getPayloadAdminToken } from '../../api/figma-api.js';
3
3
  import { validatePayloadAdminToken } from '../../auth/jwt-validator.js';
4
4
  import { getInfraEnvironment } from '../../constants.js';
5
5
  import { createCookieOptions } from './createCookieOptions.js';
6
6
  import { createDebugLogger } from './createDebugLogger.js';
7
7
  import { getCookieExpiration } from './getCookieExpiration.js';
8
8
  import { withPartitionedCookie } from './withPartitionedCookie.js';
9
- export const refreshTokens = async ({ payload, refreshToken, strategy })=>{
9
+ export const refreshTokens = async ({ headers: requestHeaders, payload, refreshToken, strategy })=>{
10
10
  const debugLogger = createDebugLogger(payload, strategy.debug);
11
11
  debugLogger.info({
12
12
  msg: 'Refreshing tokens'
13
13
  });
14
14
  const headers = new Headers();
15
- // At this point, access token is expired
16
- // but refresh token is still valid
17
- // so we will refresh both tokens
15
+ // The refresh cookie holds an OAuth access token. Use it to mint a new
16
+ // session JWT; this does not rotate an OAuth refresh token.
18
17
  try {
19
18
  // Get another Payload Admin token.
20
19
  const environmentId = payload.config.custom.figma.environmentId;
@@ -34,42 +33,54 @@ export const refreshTokens = async ({ payload, refreshToken, strategy })=>{
34
33
  debugLogger.error({
35
34
  msg: 'Error refreshing tokens'
36
35
  });
37
- return false;
38
- }
39
- if (token) {
40
- debugLogger.info({
41
- msg: 'Successfully refreshed Payload Admin token'
42
- });
43
- const expires_in = new Date(expiresAt);
44
- const cookieOptions = createCookieOptions({
45
- collection: strategy.collection,
46
- headers,
47
- pluginOptions: strategy.pluginOptions
48
- });
49
- const tokenCookie = generateCookie({
50
- ...cookieOptions,
51
- name: strategy.cookieName,
52
- expires: getCookieExpiration(expires_in),
53
- returnCookieAsObject: false,
54
- value: token
55
- });
56
- headers.append('Set-Cookie', withPartitionedCookie(tokenCookie));
57
- const decodedOauthToken = await validatePayloadAdminToken({
58
- audience: environmentId,
59
- environment: getInfraEnvironment(),
60
- token
61
- });
62
36
  return {
63
- decodedOauthToken,
64
- headers,
65
- token
37
+ status: 'temporary_failure'
66
38
  };
67
39
  }
40
+ debugLogger.info({
41
+ msg: 'Successfully refreshed Payload Admin token'
42
+ });
43
+ const decodedOauthToken = await validatePayloadAdminToken({
44
+ audience: environmentId,
45
+ environment: getInfraEnvironment(),
46
+ token
47
+ });
48
+ const expires_in = new Date(expiresAt);
49
+ const cookieOptions = createCookieOptions({
50
+ collection: strategy.collection,
51
+ headers: requestHeaders,
52
+ pluginOptions: strategy.pluginOptions
53
+ });
54
+ const tokenCookie = generateCookie({
55
+ ...cookieOptions,
56
+ name: strategy.cookieName,
57
+ expires: getCookieExpiration(expires_in),
58
+ returnCookieAsObject: false,
59
+ value: token
60
+ });
61
+ headers.append('Set-Cookie', withPartitionedCookie(tokenCookie));
62
+ return {
63
+ decodedOauthToken,
64
+ headers,
65
+ status: 'success',
66
+ token
67
+ };
68
68
  } catch (error) {
69
+ if (error instanceof FigmaApiError && [
70
+ 401,
71
+ 403,
72
+ 404
73
+ ].includes(error.statusCode ?? 0)) {
74
+ return {
75
+ status: 'rejected'
76
+ };
77
+ }
69
78
  debugLogger.error({
70
79
  err: error,
71
80
  msg: 'Error refreshing tokens'
72
81
  });
73
82
  }
74
- return false;
83
+ return {
84
+ status: 'temporary_failure'
85
+ };
75
86
  };
@@ -23,7 +23,9 @@ import { logMissingContentSystemId } from './bootstrap-preflight.js';
23
23
  import { createCacheRevalidationHooksPlugin } from './cache-revalidation-hooks.js';
24
24
  import { LIMIT_REACHED_VIEW_KEY, LIMIT_REACHED_VIEW_PATH } from './cloud-limits/routes.js';
25
25
  import { getDevCookieNames } from './dev-cookie-names.js';
26
+ import { FigmaEnvironmentError } from './environment-error.js';
26
27
  import { passesMakeViewerWriteGate, withMakeViewerWriteBaseAccessDefaults } from './make-permission-access/make-permission-access.js';
28
+ import { createMCPOAuthPlugin } from './mcp-oauth.js';
27
29
  import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
28
30
  /**
29
31
  * Worker-trusted marker injected by Figma's sites-worker after it validates the
@@ -200,18 +202,18 @@ function readCachedBootstrapData() {
200
202
  }
201
203
  const scope = readProjectScope();
202
204
  if (!scope) {
203
- throw new Error('Could not resolve the Content API URL.');
205
+ throw new FigmaEnvironmentError('Could not resolve the Content API URL.');
204
206
  }
205
207
  const message = `Could not resolve the Content API URL for environment "${scope.environmentName}" of project ${scope.projectId}.`;
206
208
  if (args.bootstrapFetched) {
207
- throw new Error(message);
209
+ throw new FigmaEnvironmentError(message);
208
210
  }
209
211
  const resolution = await resolveAndCacheBootstrap(getTokenStore(), scope.projectId, scope.environmentName);
210
212
  if (!resolution.ok) {
211
- throw new Error(`${message} ${describeBootstrapFailure(resolution.reason)}`);
213
+ throw new FigmaEnvironmentError(`${message} ${describeBootstrapFailure(resolution.reason)}`);
212
214
  }
213
215
  if (!resolution.data.contentApiUrl) {
214
- throw new Error(message);
216
+ throw new FigmaEnvironmentError(message);
215
217
  }
216
218
  return resolution.data.contentApiUrl;
217
219
  }
@@ -365,13 +367,13 @@ export async function buildFigmaConfig(config) {
365
367
  environmentId = bootstrapData?.tenantInstanceId;
366
368
  }
367
369
  if (!environmentId) {
368
- throw new Error('Environment ID could not be resolved. Set FIGMA_EID or initialize the project.');
370
+ throw new FigmaEnvironmentError('Environment ID could not be resolved. Set FIGMA_EID or initialize the project.');
369
371
  }
370
372
  if (!contentSystemId) {
371
373
  logMissingContentSystemId(bootstrapReason ?? {
372
374
  kind: 'no-config'
373
375
  });
374
- throw new Error('Content System ID could not be resolved. ' + 'Run `npx @payloadcms/figma init` to set up your project.');
376
+ throw new FigmaEnvironmentError('Content System ID could not be resolved. ' + 'Run `npx @payloadcms/figma init` to set up your project.');
375
377
  }
376
378
  // Only the content-system db adapter and cloud storage call the Content API, so a project on a
377
379
  // custom db with storage disabled needs no URL; `url` stays '' and is unused in that case.
@@ -560,11 +562,12 @@ export async function buildFigmaConfig(config) {
560
562
  usernameField: 'email'
561
563
  }
562
564
  ],
563
- ...isProduction ? {} : getDevCookieNames(contentSystemId),
565
+ ...isProduction ? {} : getDevCookieNames(contentSystemId, config.cookiePrefix),
564
566
  debug: !!process.env.DEBUG,
565
567
  disabled: false
566
568
  }),
567
569
  scheduleExtractPlugin(),
570
+ createMCPOAuthPlugin(),
568
571
  // Not folded into createStoragePlugin, which is skipped when
569
572
  // figma.storage is false and would break remote uploads for those apps.
570
573
  createSandboxUploadFetchPlugin({
@@ -5,9 +5,12 @@
5
5
  * switching environments in the same checkout; falls back to contentSystemId
6
6
  * when projectId isn't in `.env`.
7
7
  *
8
+ * Names must start with `cookiePrefix`: Payload forwards every other request
9
+ * cookie when it fetches an external upload URL.
10
+ *
8
11
  * In production, cookies are isolated by unique hostnames and this is unused.
9
12
  */
10
- export declare function getDevCookieNames(contentSystemId: string): {
13
+ export declare function getDevCookieNames(contentSystemId: string, cookiePrefix?: string): {
11
14
  cookieName: string;
12
15
  userInfoCookieName: string;
13
16
  };
@@ -6,12 +6,15 @@ import { getEnvVarSync } from '../utils/env-management.js';
6
6
  * switching environments in the same checkout; falls back to contentSystemId
7
7
  * when projectId isn't in `.env`.
8
8
  *
9
+ * Names must start with `cookiePrefix`: Payload forwards every other request
10
+ * cookie when it fetches an external upload URL.
11
+ *
9
12
  * In production, cookies are isolated by unique hostnames and this is unused.
10
- */ export function getDevCookieNames(contentSystemId) {
13
+ */ export function getDevCookieNames(contentSystemId, cookiePrefix = 'payload') {
11
14
  const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID') ?? contentSystemId;
12
15
  const suffix = projectId.slice(0, 8);
13
16
  return {
14
- cookieName: `figma-${suffix}-oauth-token`,
15
- userInfoCookieName: `figma-${suffix}-user-info`
17
+ cookieName: `${cookiePrefix}-figma-${suffix}-oauth-token`,
18
+ userInfoCookieName: `${cookiePrefix}-figma-${suffix}-user-info`
16
19
  };
17
20
  }
@@ -0,0 +1,4 @@
1
+ /** Required Figma environment configuration could not be resolved. */
2
+ export declare class FigmaEnvironmentError extends Error {
3
+ name: string;
4
+ }
@@ -0,0 +1,22 @@
1
+ import * as payload from 'payload';
2
+ /** Required Figma environment configuration could not be resolved. */ export class FigmaEnvironmentError extends Error {
3
+ name = 'FigmaEnvironmentError';
4
+ }
5
+ // Older Payload versions do not expose a CLI error hook and retain their default status 1.
6
+ if ('registerCLIExitCodeHandler' in payload && typeof payload.registerCLIExitCodeHandler === 'function') {
7
+ payload.registerCLIExitCodeHandler({
8
+ handler: (error)=>{
9
+ if (!(error instanceof FigmaEnvironmentError)) {
10
+ return undefined;
11
+ }
12
+ // Figma environments inject this status so the platform can detect
13
+ // and classify environment misconfigurations.
14
+ const rawExitCode = process.env.FIGMA_DEPLOY_FAILURE_EXIT_CODE;
15
+ if (rawExitCode === undefined || !/^\d+$/.test(rawExitCode)) {
16
+ return undefined;
17
+ }
18
+ const exitCode = Number(rawExitCode);
19
+ return exitCode >= 1 && exitCode <= 255 ? exitCode : undefined;
20
+ }
21
+ });
22
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Turns off `@payloadcms/plugin-mcp`'s OAuth login in apps that use plugin-mcp, unless the app
3
+ * sets plugin-mcp's `oauth` option itself. Newer versions of plugin-mcp turn that login on by
4
+ * default, but its default tokens need Payload's password login, which Figma apps turn off, so
5
+ * MCP clients would be asked to log in and then fail. MCP clients keep using API keys.
6
+ *
7
+ * It only sets an option on plugin-mcp, so apps without plugin-mcp don't get it. Versions of
8
+ * plugin-mcp without the option ignore it.
9
+ */
10
+ export declare const createMCPOAuthPlugin: () => import("payload").Plugin;
@@ -0,0 +1,24 @@
1
+ import { definePlugin } from 'payload';
2
+ /**
3
+ * Turns off `@payloadcms/plugin-mcp`'s OAuth login in apps that use plugin-mcp, unless the app
4
+ * sets plugin-mcp's `oauth` option itself. Newer versions of plugin-mcp turn that login on by
5
+ * default, but its default tokens need Payload's password login, which Figma apps turn off, so
6
+ * MCP clients would be asked to log in and then fail. MCP clients keep using API keys.
7
+ *
8
+ * It only sets an option on plugin-mcp, so apps without plugin-mcp don't get it. Versions of
9
+ * plugin-mcp without the option ignore it.
10
+ */ export const createMCPOAuthPlugin = definePlugin({
11
+ slug: '@payloadcms/figma/mcp-oauth',
12
+ // Before @payloadcms/plugin-mcp, which runs at order 10 and reads its options then
13
+ order: 5,
14
+ plugin: ({ config, plugins })=>{
15
+ const mcp = plugins['@payloadcms/plugin-mcp'];
16
+ if (mcp && mcp.options?.oauth === undefined) {
17
+ mcp.options = {
18
+ ...mcp.options,
19
+ oauth: false
20
+ };
21
+ }
22
+ return config;
23
+ }
24
+ });
@@ -19,14 +19,13 @@ type SandboxUploadFetchOptions = {
19
19
  * maps external hostnames to unique-local IPv6 addresses (`fc00::/7`) that
20
20
  * `safeFetch` rejects as non-unicast. A no-op elsewhere.
21
21
  *
22
- * Only a default: a collection that set `skipSafeFetch` itself keeps its value.
23
- * `externalFileHeaderFilter` is left unset on purpose, since it would replace
24
- * the cookie logic that forwards credentials for relative URLs.
22
+ * A collection that sets `skipSafeFetch` keeps its value.
23
+ * The default header filter removes current and legacy OAuth cookies from
24
+ * external requests. Trusted same-origin relative URLs retain their cookies.
25
25
  *
26
26
  * SSRF risks, bounded by the routes' auth gate and sandbox network limits:
27
- * `getExternalFile` re-validates redirects only against `pasteURL.allowList`,
28
- * any session can GET an arbitrary URL and read the body, and request cookies
29
- * reach the target.
27
+ * Payload checks each redirect against `pasteURL.allowList`.
28
+ * An authenticated session can fetch an arbitrary URL and read its body.
30
29
  */
31
30
  export declare function createSandboxUploadFetchPlugin({ userCollections }: SandboxUploadFetchOptions): (config: Config) => Config;
32
31
  export {};
@@ -12,14 +12,13 @@ import * as log from '../utils/log.js';
12
12
  * maps external hostnames to unique-local IPv6 addresses (`fc00::/7`) that
13
13
  * `safeFetch` rejects as non-unicast. A no-op elsewhere.
14
14
  *
15
- * Only a default: a collection that set `skipSafeFetch` itself keeps its value.
16
- * `externalFileHeaderFilter` is left unset on purpose, since it would replace
17
- * the cookie logic that forwards credentials for relative URLs.
15
+ * A collection that sets `skipSafeFetch` keeps its value.
16
+ * The default header filter removes current and legacy OAuth cookies from
17
+ * external requests. Trusted same-origin relative URLs retain their cookies.
18
18
  *
19
19
  * SSRF risks, bounded by the routes' auth gate and sandbox network limits:
20
- * `getExternalFile` re-validates redirects only against `pasteURL.allowList`,
21
- * any session can GET an arbitrary URL and read the body, and request cookies
22
- * reach the target.
20
+ * Payload checks each redirect against `pasteURL.allowList`.
21
+ * An authenticated session can fetch an arbitrary URL and read its body.
23
22
  */ export function createSandboxUploadFetchPlugin({ userCollections }) {
24
23
  const appOwnedSlugs = new Set((userCollections ?? []).filter((collection)=>typeof collection.upload === 'object' && 'skipSafeFetch' in collection.upload).map((collection)=>collection.slug));
25
24
  return (config)=>{
@@ -27,27 +26,36 @@ import * as log from '../utils/log.js';
27
26
  return config;
28
27
  }
29
28
  const modifiedSlugs = [];
29
+ let modified = false;
30
30
  const collections = (config.collections ?? []).map((collection)=>{
31
- if (!collection.upload || appOwnedSlugs.has(collection.slug)) {
31
+ if (!collection.upload) {
32
32
  return collection;
33
33
  }
34
- modifiedSlugs.push(collection.slug);
34
+ modified = true;
35
+ if (!appOwnedSlugs.has(collection.slug)) {
36
+ modifiedSlugs.push(collection.slug);
37
+ }
35
38
  const upload = collection.upload === true ? {} : collection.upload;
36
39
  return {
37
40
  ...collection,
38
41
  upload: {
39
42
  ...upload,
40
- skipSafeFetch: true
43
+ ...!appOwnedSlugs.has(collection.slug) ? {
44
+ skipSafeFetch: true
45
+ } : {},
46
+ externalFileHeaderFilter: upload.externalFileHeaderFilter ?? ((headers, context)=>({
47
+ // Payload supplies fresh context for each redirect hop.
48
+ cookie: (headers.cookie ?? '').split(';').filter((cookie)=>context?.isSameOrigin || !cookie.trim().startsWith(config.cookiePrefix ?? 'payload') && !/^figma-.+-(?:oauth-token(?:-refresh)?|user-info)=/.test(cookie.trim())).join(';')
49
+ }))
41
50
  }
42
51
  };
43
52
  });
44
- if (modifiedSlugs.length === 0) {
45
- return config;
53
+ if (modified) {
54
+ log.debug(`Make sandbox detected: skipSafeFetch defaults applied (${modifiedSlugs.join(', ') || 'none'}); all upload collections default to forwarding CMS cookies only to trusted same-origin relative URLs. App-defined header filters are preserved.`);
46
55
  }
47
- log.debug(`Make sandbox detected: upload collections skip safeFetch (${modifiedSlugs.join(', ')})`);
48
- return {
56
+ return modified ? {
49
57
  ...config,
50
58
  collections
51
- };
59
+ } : config;
52
60
  };
53
61
  }