@payloadcms/figma 1.0.0-beta.0 → 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 (153) 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/content-api/auth.d.ts +34 -0
  7. package/dist/content-api/auth.js +70 -0
  8. package/dist/content-api/awaitWithSignal.d.ts +2 -0
  9. package/dist/content-api/awaitWithSignal.js +27 -0
  10. package/dist/content-api/createContentApiClient.d.ts +18 -0
  11. package/dist/content-api/createContentApiClient.js +90 -0
  12. package/dist/content-api/withRateLimitRetries.d.ts +7 -0
  13. package/dist/content-api/withRateLimitRetries.js +45 -0
  14. package/dist/db-content-api/generated/content-api-types.d.ts +247 -0
  15. package/dist/db-content-api/index.d.ts +5 -5
  16. package/dist/db-content-api/index.js +46 -16
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.js +1 -0
  19. package/dist/oauth/components/FigmaAvatar/index.js +3 -2
  20. package/dist/oauth/components/FigmaAvatarCell/index.js +3 -1
  21. package/dist/oauth/components/LoginButton/index.js +8 -4
  22. package/dist/oauth/components/LogoutButton/index.js +3 -2
  23. package/dist/oauth/defaults.js +2 -2
  24. package/dist/oauth/endpoints/getLoginEndpoint.js +2 -5
  25. package/dist/oauth/hooks/me.d.ts +4 -3
  26. package/dist/oauth/hooks/me.js +6 -52
  27. package/dist/oauth/hooks/refresh.js +9 -1
  28. package/dist/oauth/index.js +3 -3
  29. package/dist/oauth/strategy/index.d.ts +3 -0
  30. package/dist/oauth/strategy/index.js +49 -3
  31. package/dist/oauth/utilities/clearCookie.d.ts +1 -0
  32. package/dist/oauth/utilities/clearCookie.js +13 -9
  33. package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
  34. package/dist/oauth/utilities/clearSessionCookies.js +17 -0
  35. package/dist/oauth/utilities/getAuthorizeURL.js +1 -2
  36. package/dist/oauth/utilities/mergeHeaders.js +11 -23
  37. package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
  38. package/dist/oauth/utilities/refreshTokens.js +45 -34
  39. package/dist/oauth/utilities/resolvePayloadRedirect.d.ts +13 -0
  40. package/dist/oauth/utilities/resolvePayloadRedirect.js +30 -0
  41. package/dist/plugin/build-config.js +16 -13
  42. package/dist/plugin/cloud-limits/CloudLimitModal/index.js +1 -1
  43. package/dist/plugin/cloud-limits/shared.d.ts +5 -1
  44. package/dist/plugin/cloud-limits/utilities/toasts.d.ts +2 -1
  45. package/dist/plugin/dev-cookie-names.d.ts +4 -1
  46. package/dist/plugin/dev-cookie-names.js +6 -3
  47. package/dist/plugin/environment-error.d.ts +4 -0
  48. package/dist/plugin/environment-error.js +22 -0
  49. package/dist/plugin/mcp-oauth.d.ts +10 -0
  50. package/dist/plugin/mcp-oauth.js +24 -0
  51. package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
  52. package/dist/plugin/sandbox-upload-fetch.js +22 -14
  53. package/dist/scss.d.js +1 -1
  54. package/dist/storage-content-api/api-types.d.ts +22 -1
  55. package/dist/storage-content-api/api-types.js +2 -1
  56. package/dist/storage-content-api/client.d.ts +3 -3
  57. package/dist/storage-content-api/client.js +13 -35
  58. package/dist/storage-content-api/index.js +20 -21
  59. package/dist/storage-content-api/staticHandler.js +4 -1
  60. package/dist/storage-content-api/types.d.ts +2 -2
  61. package/dist/translations/ar.d.ts +9 -0
  62. package/dist/translations/ar.js +10 -1
  63. package/dist/translations/az.d.ts +9 -0
  64. package/dist/translations/az.js +10 -1
  65. package/dist/translations/bg.d.ts +9 -0
  66. package/dist/translations/bg.js +10 -1
  67. package/dist/translations/bnBd.d.ts +9 -0
  68. package/dist/translations/bnBd.js +10 -1
  69. package/dist/translations/bnIn.d.ts +9 -0
  70. package/dist/translations/bnIn.js +10 -1
  71. package/dist/translations/ca.d.ts +9 -0
  72. package/dist/translations/ca.js +10 -1
  73. package/dist/translations/cs.d.ts +9 -0
  74. package/dist/translations/cs.js +10 -1
  75. package/dist/translations/da.d.ts +9 -0
  76. package/dist/translations/da.js +10 -1
  77. package/dist/translations/de.d.ts +9 -0
  78. package/dist/translations/de.js +10 -1
  79. package/dist/translations/en.d.ts +9 -0
  80. package/dist/translations/en.js +10 -1
  81. package/dist/translations/es.d.ts +9 -0
  82. package/dist/translations/es.js +15 -6
  83. package/dist/translations/et.d.ts +9 -0
  84. package/dist/translations/et.js +10 -1
  85. package/dist/translations/fa.d.ts +9 -0
  86. package/dist/translations/fa.js +10 -1
  87. package/dist/translations/fr.d.ts +9 -0
  88. package/dist/translations/fr.js +10 -1
  89. package/dist/translations/he.d.ts +9 -0
  90. package/dist/translations/he.js +10 -1
  91. package/dist/translations/hr.d.ts +9 -0
  92. package/dist/translations/hr.js +10 -1
  93. package/dist/translations/hu.d.ts +9 -0
  94. package/dist/translations/hu.js +10 -1
  95. package/dist/translations/hy.d.ts +9 -0
  96. package/dist/translations/hy.js +10 -1
  97. package/dist/translations/id.d.ts +9 -0
  98. package/dist/translations/id.js +10 -1
  99. package/dist/translations/index.d.ts +400 -3
  100. package/dist/translations/is.d.ts +9 -0
  101. package/dist/translations/is.js +10 -1
  102. package/dist/translations/it.d.ts +9 -0
  103. package/dist/translations/it.js +10 -1
  104. package/dist/translations/ja.d.ts +9 -0
  105. package/dist/translations/ja.js +14 -5
  106. package/dist/translations/ko.d.ts +9 -0
  107. package/dist/translations/ko.js +16 -7
  108. package/dist/translations/lt.d.ts +9 -0
  109. package/dist/translations/lt.js +10 -1
  110. package/dist/translations/lv.d.ts +9 -0
  111. package/dist/translations/lv.js +10 -1
  112. package/dist/translations/my.d.ts +9 -0
  113. package/dist/translations/my.js +10 -1
  114. package/dist/translations/nb.d.ts +9 -0
  115. package/dist/translations/nb.js +10 -1
  116. package/dist/translations/nl.d.ts +9 -0
  117. package/dist/translations/nl.js +10 -1
  118. package/dist/translations/pl.d.ts +9 -0
  119. package/dist/translations/pl.js +10 -1
  120. package/dist/translations/pt.d.ts +9 -0
  121. package/dist/translations/pt.js +15 -6
  122. package/dist/translations/ro.d.ts +9 -0
  123. package/dist/translations/ro.js +10 -1
  124. package/dist/translations/rs.d.ts +9 -0
  125. package/dist/translations/rs.js +10 -1
  126. package/dist/translations/rsLatin.d.ts +9 -0
  127. package/dist/translations/rsLatin.js +10 -1
  128. package/dist/translations/ru.d.ts +9 -0
  129. package/dist/translations/ru.js +10 -1
  130. package/dist/translations/sk.d.ts +9 -0
  131. package/dist/translations/sk.js +10 -1
  132. package/dist/translations/sl.d.ts +9 -0
  133. package/dist/translations/sl.js +10 -1
  134. package/dist/translations/sv.d.ts +9 -0
  135. package/dist/translations/sv.js +10 -1
  136. package/dist/translations/ta.d.ts +9 -0
  137. package/dist/translations/ta.js +10 -1
  138. package/dist/translations/th.d.ts +9 -0
  139. package/dist/translations/th.js +10 -1
  140. package/dist/translations/tr.d.ts +9 -0
  141. package/dist/translations/tr.js +10 -1
  142. package/dist/translations/uk.d.ts +9 -0
  143. package/dist/translations/uk.js +10 -1
  144. package/dist/translations/vi.d.ts +9 -0
  145. package/dist/translations/vi.js +10 -1
  146. package/dist/translations/zh.d.ts +9 -0
  147. package/dist/translations/zh.js +10 -1
  148. package/dist/translations/zhTw.d.ts +9 -0
  149. package/dist/translations/zhTw.js +10 -1
  150. package/dist/utils/env-management.js +7 -0
  151. package/package.json +20 -22
  152. package/dist/db-content-api/utilities/auth.d.ts +0 -29
  153. package/dist/db-content-api/utilities/auth.js +0 -82
@@ -97,7 +97,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
97
97
  name: 'email',
98
98
  type: 'email',
99
99
  admin: {
100
- description: 'Managed by Figma',
100
+ description: ({ t })=>t('figma:managedByFigma'),
101
101
  readOnly: true
102
102
  },
103
103
  unique: true
@@ -114,7 +114,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
114
114
  admin: {
115
115
  ...usernameField.admin || {},
116
116
  ...usernameField.name === 'email' ? {
117
- description: 'Managed by Figma'
117
+ description: ({ t })=>t('figma:managedByFigma')
118
118
  } : {},
119
119
  readOnly: true
120
120
  }
@@ -225,7 +225,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
225
225
  // Do not inject the me hook if the usePayloadJWT option is enabled
226
226
  ...!collectionOptions.usePayloadJWT ? [
227
227
  getMeHook({
228
- cookieName
228
+ strategy
229
229
  })
230
230
  ] : []
231
231
  ],
@@ -14,6 +14,8 @@ export interface Options {
14
14
  verify: VerifyFunction;
15
15
  }
16
16
  export declare class Strategy {
17
+ /** Keeps /me aligned with authentication-time renewal without changing request cookies. */
18
+ authenticatedTokenExpirations: WeakMap<Headers, number | undefined>;
17
19
  clientID: string;
18
20
  collection: CollectionConfig;
19
21
  collectionOptions: CollectionOptions;
@@ -38,6 +40,7 @@ export declare class Strategy {
38
40
  pluginOptions: PluginOptions;
39
41
  verify: VerifyFunction;
40
42
  constructor(options: Options);
43
+ private setTokenExpiration;
41
44
  authenticate({ canSetHeaders, headers, payload, }: AuthStrategyFunctionArgs): Promise<AuthStrategyResult>;
42
45
  ensureMeta(): Promise<void>;
43
46
  fetchMeta(): Promise<void>;
@@ -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
  };
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Applies the `payloadRedirect` cookie (Payload's `?redirect=` login param, saved by
3
+ * `LoginButton`) to the post-login redirect URL.
4
+ *
5
+ * Payload sets `?redirect=` to the full admin path, e.g. `/admin/collections/posts`, or to just a
6
+ * query string when login started at the admin root. Appending a path to the admin URL would
7
+ * double the admin route (`/admin/admin/collections/posts`), so paths are resolved from the
8
+ * origin instead. Unsafe values, including absolute URLs, are ignored.
9
+ *
10
+ * @example resolvePayloadRedirect('/admin/collections/posts', 'https://site/admin') // 'https://site/admin/collections/posts'
11
+ * @example resolvePayloadRedirect('?embed=true', 'https://site/admin') // 'https://site/admin?embed=true'
12
+ */
13
+ export declare function resolvePayloadRedirect(payloadRedirect: string, redirectURL: string): string;
@@ -0,0 +1,30 @@
1
+ import { formatAdminURL, getSafeRedirect } from 'payload/shared';
2
+ /**
3
+ * Applies the `payloadRedirect` cookie (Payload's `?redirect=` login param, saved by
4
+ * `LoginButton`) to the post-login redirect URL.
5
+ *
6
+ * Payload sets `?redirect=` to the full admin path, e.g. `/admin/collections/posts`, or to just a
7
+ * query string when login started at the admin root. Appending a path to the admin URL would
8
+ * double the admin route (`/admin/admin/collections/posts`), so paths are resolved from the
9
+ * origin instead. Unsafe values, including absolute URLs, are ignored.
10
+ *
11
+ * @example resolvePayloadRedirect('/admin/collections/posts', 'https://site/admin') // 'https://site/admin/collections/posts'
12
+ * @example resolvePayloadRedirect('?embed=true', 'https://site/admin') // 'https://site/admin?embed=true'
13
+ */ export function resolvePayloadRedirect(payloadRedirect, redirectURL) {
14
+ if (payloadRedirect.startsWith('?')) {
15
+ return redirectURL + payloadRedirect;
16
+ }
17
+ const path = getSafeRedirect({
18
+ fallbackTo: '',
19
+ redirectTo: payloadRedirect
20
+ });
21
+ if (!path) {
22
+ return redirectURL;
23
+ }
24
+ // `adminRoute: '/'` adds no route segment, leaving the origin, any Next.js basePath, and `path`.
25
+ return formatAdminURL({
26
+ adminRoute: '/',
27
+ path: path,
28
+ serverURL: redirectURL
29
+ });
30
+ }
@@ -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
@@ -42,7 +44,7 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
42
44
  admin: {
43
45
  readOnly: true
44
46
  },
45
- label: 'Name'
47
+ label: ({ t })=>t('general:name')
46
48
  },
47
49
  {
48
50
  name: 'figmaImageUrl',
@@ -57,7 +59,7 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
57
59
  hidden: true,
58
60
  readOnly: true
59
61
  },
60
- label: 'Profile Picture'
62
+ label: ({ t })=>t('figma:profilePicture')
61
63
  },
62
64
  // Virtual (never persisted): populated per-request from the session JWT. The
63
65
  // afterRead hook surfaces the claim on the requester's OWN user record only —
@@ -79,7 +81,7 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
79
81
  ({ data, req })=>data?.id !== undefined && req.user?.id === data.id ? req.user.userGroups : undefined
80
82
  ]
81
83
  },
82
- label: 'User Groups',
84
+ label: ({ t })=>t('figma:userGroups'),
83
85
  virtual: true
84
86
  },
85
87
  // KEEP_IN_SYNC(sinatra/controllers/api/api_payload_control_plane.rb) — resolve_make_permission
@@ -97,14 +99,14 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
97
99
  ({ data, req })=>data?.id !== undefined && req.user?.id === data.id ? req.user.makePermission : undefined
98
100
  ]
99
101
  },
100
- label: 'Make Permission',
102
+ label: ({ t })=>t('figma:makePermission'),
101
103
  options: [
102
104
  {
103
- label: 'View',
105
+ label: ({ t })=>t('figma:view'),
104
106
  value: 'view'
105
107
  },
106
108
  {
107
- label: 'Edit',
109
+ label: ({ t })=>t('general:edit'),
108
110
  value: 'edit'
109
111
  }
110
112
  ],
@@ -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({
@@ -54,7 +54,7 @@ export function FigmaCloudLimitDocumentCountModal({ collectionLabel, collectionL
54
54
  onRetry();
55
55
  },
56
56
  size: "medium",
57
- children: t('figma:cloudLimitModalRetry')
57
+ children: t('general:retry')
58
58
  })
59
59
  ]
60
60
  })
@@ -7,4 +7,8 @@ export type CloudLimitErrorCode = (typeof cloudLimitErrorCodes)[keyof typeof clo
7
7
  export declare function isCloudLimitErrorCode(code: unknown): code is CloudLimitErrorCode;
8
8
  export declare function getCloudLimitErrorCode(json: unknown): CloudLimitErrorCode | undefined;
9
9
  export declare const cloudLimitDocumentCountModalSlug = "figma-cloud-limit-document-count";
10
- export declare const cloudLimitToastKeyByCode: Record<CloudLimitErrorCode, string>;
10
+ export declare const cloudLimitToastKeyByCode: {
11
+ "cloud_limit.cms_assets_bytes_exceeded": "figma:cloudLimitAssetStorageError";
12
+ "cloud_limit.document_count_exceeded": "figma:cloudLimitDocumentCountError";
13
+ "cloud_limit.per_document_data_bytes_exceeded": "figma:cloudLimitDocumentDataSizeError";
14
+ };
@@ -1,4 +1,5 @@
1
+ import type { FigmaTranslationKeys } from '../../../translations/index.js';
1
2
  import type { CloudLimitErrorCode } from '../shared.js';
2
- export type Translate = (key: string) => string;
3
+ export type Translate = (key: FigmaTranslationKeys) => string;
3
4
  export declare function dismissSubmittingToast(label: string): void;
4
5
  export declare function showCloudLimitToast(code: CloudLimitErrorCode, translate: Translate): void;
@@ -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
  };