@payloadcms/figma 0.1.0-alpha.10 → 0.1.0-alpha.12

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 (73) hide show
  1. package/dist/api/control-plane.d.ts +11 -0
  2. package/dist/api/control-plane.js +26 -0
  3. package/dist/auth/headless-oauth-flow.js +4 -0
  4. package/dist/auth/oauth-flow.js +17 -0
  5. package/dist/auth/refresh.js +12 -12
  6. package/dist/auth/requested-scopes.d.ts +1 -0
  7. package/dist/auth/requested-scopes.js +3 -0
  8. package/dist/auth/token-store.d.ts +16 -0
  9. package/dist/auth/token-store.js +33 -0
  10. package/dist/auth/types.d.ts +5 -3
  11. package/dist/commands/bootstrap.js +3 -0
  12. package/dist/commands/init.js +71 -1
  13. package/dist/commands/upgrade.js +65 -1
  14. package/dist/commands/upload-schema.js +3 -4
  15. package/dist/config/oauth.js +6 -1
  16. package/dist/constants.d.ts +0 -2
  17. package/dist/constants.js +0 -3
  18. package/dist/db-content-api/utilities/data/index.js +6 -0
  19. package/dist/db-content-api/utilities/schema/buildDocumentSchema.js +9 -4
  20. package/dist/plugin/build-config.d.ts +9 -1
  21. package/dist/plugin/build-config.js +158 -17
  22. package/dist/plugin/cloud-limits/CloudLimitModal/index.d.ts +2 -1
  23. package/dist/plugin/cloud-limits/icons/ExternalLinkIcon.d.ts +2 -1
  24. package/dist/storage-content-api/api-types.d.ts +5 -2
  25. package/dist/storage-content-api/buildBaseMediaResponseHeaders.d.ts +1 -0
  26. package/dist/storage-content-api/buildBaseMediaResponseHeaders.js +8 -0
  27. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.d.ts +12 -0
  28. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.js +26 -0
  29. package/dist/storage-content-api/buildMediaRequestHeaders.d.ts +1 -0
  30. package/dist/storage-content-api/buildMediaRequestHeaders.js +14 -0
  31. package/dist/storage-content-api/buildMediaResponseHeaders.d.ts +4 -0
  32. package/dist/storage-content-api/buildMediaResponseHeaders.js +52 -0
  33. package/dist/storage-content-api/client-uploads/generate.d.ts +7 -3
  34. package/dist/storage-content-api/client-uploads/generate.js +20 -20
  35. package/dist/storage-content-api/copyFile.d.ts +16 -0
  36. package/dist/storage-content-api/copyFile.js +90 -0
  37. package/dist/storage-content-api/deleteFile.d.ts +8 -0
  38. package/dist/storage-content-api/deleteFile.js +18 -0
  39. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.d.ts +3 -3
  40. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.js +10 -4
  41. package/dist/storage-content-api/getMediaType.d.ts +1 -0
  42. package/dist/storage-content-api/getMediaType.js +3 -0
  43. package/dist/storage-content-api/handleUpload.d.ts +1 -2
  44. package/dist/storage-content-api/handleUpload.js +13 -157
  45. package/dist/storage-content-api/hasSupportedContentEncoding.d.ts +1 -0
  46. package/dist/storage-content-api/hasSupportedContentEncoding.js +6 -0
  47. package/dist/storage-content-api/index.js +16 -8
  48. package/dist/storage-content-api/mediaErrorResponse.d.ts +1 -0
  49. package/dist/storage-content-api/mediaErrorResponse.js +12 -0
  50. package/dist/storage-content-api/shouldAttachMedia.d.ts +1 -0
  51. package/dist/storage-content-api/shouldAttachMedia.js +34 -0
  52. package/dist/storage-content-api/staticHandler.d.ts +2 -1
  53. package/dist/storage-content-api/staticHandler.js +85 -31
  54. package/dist/storage-content-api/uploadFileData.d.ts +10 -0
  55. package/dist/storage-content-api/uploadFileData.js +145 -0
  56. package/dist/utils/cache-bootstrap.js +1 -0
  57. package/dist/utils/env-management.d.ts +15 -0
  58. package/dist/utils/env-management.js +47 -0
  59. package/dist/utils/load-payload-config.js +1 -6
  60. package/dist/utils/payload-config-ast.d.ts +5 -0
  61. package/dist/utils/payload-config-ast.js +73 -4
  62. package/dist/utils/payload-config-modifier.js +3 -0
  63. package/dist/utils/payload-secret.d.ts +28 -0
  64. package/dist/utils/payload-secret.js +34 -0
  65. package/package.json +15 -13
  66. package/dist/storage-content-api/handleDelete.d.ts +0 -7
  67. package/dist/storage-content-api/handleDelete.js +0 -15
  68. package/dist/storage-content-api/utilities/getSafeFilename.d.ts +0 -11
  69. package/dist/storage-content-api/utilities/getSafeFilename.js +0 -59
  70. package/dist/storage-content-api/utilities/index.d.ts +0 -2
  71. package/dist/storage-content-api/utilities/index.js +0 -2
  72. package/dist/storage-content-api/utilities/parseUploadReference.d.ts +0 -17
  73. package/dist/storage-content-api/utilities/parseUploadReference.js +0 -27
@@ -132,6 +132,8 @@ export declare function performDeployment(credential: AuthCredential, tenantId:
132
132
  * A single environment returned by the bootstrap endpoint
133
133
  */
134
134
  export type BootstrapEnvironment = {
135
+ /** Regional Content API base URL. Absent when the server predates the field. */
136
+ contentApiUrl?: string;
135
137
  contentSystemId: string;
136
138
  name: string;
137
139
  tenantInstanceId: string;
@@ -155,6 +157,15 @@ export type BootstrapInfo = {
155
157
  * @param environmentName - Optional environment name filter
156
158
  */
157
159
  export declare function getBootstrapInfo(credential: AuthCredential, cmsResourceId: string, environmentName?: string): Promise<BootstrapInfo>;
160
+ /**
161
+ * Fetch the decrypted value of a tenant environment variable by name.
162
+ * Maps to: GET /v1/environments/:tenant_instance_id/environment_variables/by_name?name=...
163
+ *
164
+ * Only variables with `user_visibility: name_and_value` are returned; the
165
+ * endpoint answers 404 otherwise. Used by init and buildFigmaConfig to
166
+ * resolve PAYLOAD_SECRET on developer machines.
167
+ */
168
+ export declare function getEnvironmentVariableByName(credential: AuthCredential, tenantInstanceId: string, name: string): Promise<string>;
158
169
  /**
159
170
  * Resolve a CMS Resource ID from a legacy dataset (content system) ID.
160
171
  * Maps to: GET /v1/cms/dataset/:datasetId
@@ -278,6 +278,7 @@ import { controlPlaneFetch } from './control-plane-fetch.js';
278
278
  return {
279
279
  environments: data.meta.environments.map((env)=>({
280
280
  name: env.name,
281
+ contentApiUrl: env.content_api_url,
281
282
  contentSystemId: env.content_system_id,
282
283
  tenantInstanceId: env.tenant_instance_id
283
284
  })),
@@ -287,6 +288,31 @@ import { controlPlaneFetch } from './control-plane-fetch.js';
287
288
  }
288
289
  };
289
290
  }
291
+ /**
292
+ * Fetch the decrypted value of a tenant environment variable by name.
293
+ * Maps to: GET /v1/environments/:tenant_instance_id/environment_variables/by_name?name=...
294
+ *
295
+ * Only variables with `user_visibility: name_and_value` are returned; the
296
+ * endpoint answers 404 otherwise. Used by init and buildFigmaConfig to
297
+ * resolve PAYLOAD_SECRET on developer machines.
298
+ */ export async function getEnvironmentVariableByName(credential, tenantInstanceId, name) {
299
+ const shouldMock = process.env.FIGMA_MOCK_CONTROL_PLANE === 'true';
300
+ if (shouldMock) {
301
+ log.debug('Using mock Control Plane API for getEnvironmentVariableByName (FIGMA_MOCK_CONTROL_PLANE === "true")');
302
+ return `mock-${name.toLowerCase()}-${tenantInstanceId}`;
303
+ }
304
+ const url = `${getControlPlaneBaseUrl()}/v1/environments/${encodeURIComponent(tenantInstanceId)}` + `/environment_variables/by_name?name=${encodeURIComponent(name)}`;
305
+ log.debug(`Calling getEnvironmentVariableByName API at ${url}`);
306
+ const response = await controlPlaneFetch({
307
+ context: `get environment variable ${name}`,
308
+ options: {
309
+ headers: getAuthHeaders(credential)
310
+ },
311
+ url
312
+ });
313
+ const data = await response.json();
314
+ return data.meta.value;
315
+ }
290
316
  /**
291
317
  * Resolve a CMS Resource ID from a legacy dataset (content system) ID.
292
318
  * Maps to: GET /v1/cms/dataset/:datasetId
@@ -4,6 +4,7 @@ import { buildAuthorizationUrl } from './browser.js';
4
4
  import { parsePastedCode } from './paste-code.js';
5
5
  import { generatePKCEPair } from './pkce.js';
6
6
  import { exchangeCodeForTokens } from './refresh.js';
7
+ import { hasRequestedScopes } from './requested-scopes.js';
7
8
  const HEADLESS_OAUTH_SESSION_TTL_MS = 10 * 60 * 1000;
8
9
  export class HeadlessOAuthFlowError extends Error {
9
10
  constructor(message){
@@ -58,6 +59,9 @@ export class HeadlessOAuthFlowError extends Error {
58
59
  }
59
60
  const code = parsePastedCode(callbackUrl, session.state);
60
61
  const tokens = await exchangeCodeForTokens(code, session.codeVerifier, session.redirectUri, session.clientId);
62
+ if (!hasRequestedScopes(tokens.scopes, getOAuthConfig().scopes)) {
63
+ throw new HeadlessOAuthFlowError('Authorization did not grant all requested Cloud scopes');
64
+ }
61
65
  tokenStore.setTokens(tokens);
62
66
  return {
63
67
  tokens,
@@ -7,6 +7,7 @@ import { CallbackError, CallbackServer } from './callback-server.js';
7
7
  import { parsePastedCode, validatePastedCode } from './paste-code.js';
8
8
  import { generatePKCEPair } from './pkce.js';
9
9
  import { exchangeCodeForTokens, refreshAccessToken, TokenRefreshError } from './refresh.js';
10
+ import { hasRequestedScopes } from './requested-scopes.js';
10
11
  /**
11
12
  * Error during OAuth flow
12
13
  */ export class OAuthFlowError extends Error {
@@ -130,6 +131,9 @@ import { exchangeCodeForTokens, refreshAccessToken, TokenRefreshError } from './
130
131
  } catch (error) {
131
132
  throw new OAuthFlowError('Failed to exchange authorization code for tokens', error instanceof Error ? error : undefined);
132
133
  }
134
+ if (!hasRequestedScopes(tokens.scopes, scopes)) {
135
+ throw new OAuthFlowError('Authorization did not grant all requested Cloud scopes');
136
+ }
133
137
  // Store tokens
134
138
  try {
135
139
  tokenStore.setTokens(tokens);
@@ -162,6 +166,13 @@ import { exchangeCodeForTokens, refreshAccessToken, TokenRefreshError } from './
162
166
  * @returns Promise resolving to AuthCredential (wrapped access token) or null if no valid tokens
163
167
  * @throws OAuthFlowError if refresh fails
164
168
  */ export async function getValidOAuthAccessToken(tokenStore) {
169
+ const cached = tokenStore.getOauthInfo();
170
+ const requiredScopes = getOAuthConfig().scopes;
171
+ // Older cached grants lack scope metadata or the Cloud capabilities. Refreshing
172
+ // them cannot add consent, so start a new authorization flow instead.
173
+ if (cached && !hasRequestedScopes(cached.scopes, requiredScopes)) {
174
+ return null;
175
+ }
165
176
  // Check if we have valid tokens
166
177
  if (tokenStore.hasValidOauthToken()) {
167
178
  const token = tokenStore.getCurrentOauthToken();
@@ -179,6 +190,9 @@ import { exchangeCodeForTokens, refreshAccessToken, TokenRefreshError } from './
179
190
  try {
180
191
  const tokens = await refreshAccessToken(refreshToken);
181
192
  tokenStore.setTokens(tokens);
193
+ if (!hasRequestedScopes(tokens.scopes, requiredScopes)) {
194
+ return null;
195
+ }
182
196
  return {
183
197
  type: 'oauth',
184
198
  token: tokens.accessToken
@@ -190,6 +204,9 @@ import { exchangeCodeForTokens, refreshAccessToken, TokenRefreshError } from './
190
204
  try {
191
205
  const tokens = await refreshAccessToken(refreshToken);
192
206
  tokenStore.setTokens(tokens);
207
+ if (!hasRequestedScopes(tokens.scopes, requiredScopes)) {
208
+ return null;
209
+ }
193
210
  return {
194
211
  type: 'oauth',
195
212
  token: tokens.accessToken
@@ -1,5 +1,8 @@
1
1
  /* eslint-disable perfectionist/sort-objects */ import { getOAuthConfig } from '../config/oauth.js';
2
2
  import * as log from '../utils/log.js';
3
+ function parseGrantedScopes(scope) {
4
+ return scope?.split(/[\s,]+/).filter(Boolean);
5
+ }
3
6
  /**
4
7
  * Error thrown when token refresh fails
5
8
  */ export class TokenRefreshError extends Error {
@@ -50,15 +53,17 @@ import * as log from '../utils/log.js';
50
53
  }
51
54
  const data = await response.json();
52
55
  // Validate response contains required fields
53
- if (!data.access_token || !data.refresh_token || !data.expires_in) {
56
+ if (!data.access_token || !data.expires_in) {
54
57
  throw new TokenRefreshError('Invalid token response: missing required fields');
55
58
  }
56
59
  // Convert response to our internal token format
57
60
  const expiresAt = Date.now() + data.expires_in * 1000;
58
61
  return {
59
62
  accessToken: data.access_token,
60
- refreshToken: data.refresh_token,
63
+ refreshToken: data.refresh_token ?? refreshToken,
61
64
  expiresAt,
65
+ scopes: parseGrantedScopes(data.scope),
66
+ tokenType: data.token_type,
62
67
  userId: data.user_id_string
63
68
  };
64
69
  } catch (error) {
@@ -99,12 +104,7 @@ import * as log from '../utils/log.js';
99
104
  const headers = {
100
105
  'Content-Type': 'application/x-www-form-urlencoded'
101
106
  };
102
- // Debug logging
103
- log.debug(`Token exchange request: ${JSON.stringify({
104
- url: oauthConfig.tokenUrl,
105
- headers,
106
- body: params.toString()
107
- })}`);
107
+ log.debug(`Token exchange request to ${oauthConfig.tokenUrl}`);
108
108
  const response = await fetch(oauthConfig.tokenUrl, {
109
109
  method: 'POST',
110
110
  headers,
@@ -117,17 +117,15 @@ import * as log from '../utils/log.js';
117
117
  })}`);
118
118
  if (!response.ok) {
119
119
  const errorText = await response.text();
120
- log.debug(`Error response body: ${errorText}`);
120
+ log.debug(`Token exchange rejected with status ${response.status}`);
121
121
  throw new TokenRefreshError(`Token exchange failed: ${response.statusText}. ${errorText}`, response.status);
122
122
  }
123
123
  const data = await response.json();
124
124
  log.debug(`Token response: ${JSON.stringify({
125
- access_token: data.access_token,
126
125
  token_type: data.token_type,
127
126
  expires_in: data.expires_in,
128
127
  scope: data.scope,
129
- user_id_string: data.user_id_string,
130
- refresh_token: data.refresh_token?.substring(0, 10) + '...'
128
+ user_id_string: data.user_id_string
131
129
  })}`);
132
130
  // Validate response contains required fields
133
131
  if (!data.access_token || !data.refresh_token || !data.expires_in) {
@@ -139,6 +137,8 @@ import * as log from '../utils/log.js';
139
137
  accessToken: data.access_token,
140
138
  refreshToken: data.refresh_token,
141
139
  expiresAt,
140
+ scopes: parseGrantedScopes(data.scope),
141
+ tokenType: data.token_type,
142
142
  userId: data.user_id_string
143
143
  };
144
144
  } catch (error) {
@@ -0,0 +1 @@
1
+ export declare function hasRequestedScopes(granted: readonly string[] | undefined, required: readonly string[]): boolean;
@@ -0,0 +1,3 @@
1
+ export function hasRequestedScopes(granted, required) {
2
+ return !!granted && required.every((scope)=>granted.includes(scope));
3
+ }
@@ -64,6 +64,22 @@ export declare class TokenStore {
64
64
  getBootstrapData(projectId: string, environmentName: string): BootstrapData | null;
65
65
  setBootstrapData(projectId: string, environmentName: string, data: BootstrapData): void;
66
66
  clearBootstrapData(projectId: string, environmentName: string): void;
67
+ /**
68
+ * PAYLOAD_SECRET is fetched from the Control Plane during `init` and
69
+ * cached here per (projectId, environmentName). buildFigmaConfig reads
70
+ * it at local dev startup when process.env.PAYLOAD_SECRET is unset.
71
+ * Platform-injected in Lambda, so this path is never hit there.
72
+ */
73
+ getPayloadSecret({ projectInfo }?: {
74
+ projectInfo?: ProjectStoreScope;
75
+ }): null | string;
76
+ setPayloadSecret({ projectInfo, secret, }: {
77
+ projectInfo?: ProjectStoreScope;
78
+ secret: string;
79
+ }): void;
80
+ clearPayloadSecret({ projectInfo }?: {
81
+ projectInfo?: ProjectStoreScope;
82
+ }): void;
67
83
  private buildOAuthConfigName;
68
84
  private buildOAuthStoreCwd;
69
85
  private buildProjectStoreConfigName;
@@ -354,6 +354,39 @@ const PROJECT_STORE_SCHEMA_VERSION = 1;
354
354
  });
355
355
  config.delete('bootstrapData');
356
356
  }
357
+ /**
358
+ * PAYLOAD_SECRET is fetched from the Control Plane during `init` and
359
+ * cached here per (projectId, environmentName). buildFigmaConfig reads
360
+ * it at local dev startup when process.env.PAYLOAD_SECRET is unset.
361
+ * Platform-injected in Lambda, so this path is never hit there.
362
+ */ getPayloadSecret({ projectInfo } = {}) {
363
+ const resolvedProjectInfo = projectInfo ?? this.getProjectInfoFromEnv();
364
+ if (!resolvedProjectInfo) {
365
+ return null;
366
+ }
367
+ const config = this.getProjectStore(resolvedProjectInfo);
368
+ return this.safeGet({
369
+ config,
370
+ key: 'payloadSecret'
371
+ }) ?? null;
372
+ }
373
+ setPayloadSecret({ projectInfo, secret }) {
374
+ const resolvedProjectInfo = projectInfo ?? this.getProjectInfoFromEnv();
375
+ if (!resolvedProjectInfo) {
376
+ throw new Error('Cannot set payload secret: FIGMA_PROJECT_ID and FIGMA_ENVIRONMENT_NAME must be set');
377
+ }
378
+ const config = this.getProjectStore(resolvedProjectInfo);
379
+ config.set('_schemaVersion', PROJECT_STORE_SCHEMA_VERSION);
380
+ config.set('payloadSecret', secret);
381
+ }
382
+ clearPayloadSecret({ projectInfo } = {}) {
383
+ const resolvedProjectInfo = projectInfo ?? this.getProjectInfoFromEnv();
384
+ if (!resolvedProjectInfo) {
385
+ return;
386
+ }
387
+ const config = this.getProjectStore(resolvedProjectInfo);
388
+ config.delete('payloadSecret');
389
+ }
357
390
  buildOAuthConfigName() {
358
391
  // For test isolation: if using a custom config name, use it as-is with -oauth suffix
359
392
  // Otherwise use the standard naming that includes environment
@@ -5,7 +5,7 @@ import type { Environment } from '../constants.js';
5
5
  * Standard OAuth2 scopes for user-level permissions
6
6
  * @see https://www.figma.com/developers/api#oauth2
7
7
  */
8
- export type FigmaOAuthScope = 'current_user:read' | 'file_comments:read' | 'file_comments:write' | 'file_content:read' | 'file_dev_resources:read' | 'file_dev_resources:write' | 'file_metadata:read' | 'file_variables:read' | 'file_variables:write' | 'file_versions:read' | 'files:read' | 'library_analytics:read' | 'library_assets:read' | 'library_content:read' | 'projects:read' | 'team_library_content:read' | 'webhooks:read' | 'webhooks:write';
8
+ export type FigmaOAuthScope = 'cloud:content:read_write' | 'cloud:create' | 'cloud:deploy' | 'cloud:read' | 'cloud:secrets:read' | 'current_user:read' | 'file_comments:read' | 'file_comments:write' | 'file_content:read' | 'file_dev_resources:read' | 'file_dev_resources:write' | 'file_metadata:read' | 'file_variables:read' | 'file_variables:write' | 'file_versions:read' | 'files:read' | 'library_analytics:read' | 'library_assets:read' | 'library_content:read' | 'projects:read' | 'team_library_content:read' | 'webhooks:read' | 'webhooks:write';
9
9
  /**
10
10
  * Organization-level OAuth2 scopes
11
11
  * Requires organization admin permissions
@@ -53,8 +53,8 @@ export interface FigmaTokenResponse {
53
53
  access_token: string;
54
54
  /** Token expiration time in seconds */
55
55
  expires_in: number;
56
- /** OAuth2 refresh token */
57
- refresh_token: string;
56
+ /** OAuth2 refresh token; omitted when refreshing an existing grant */
57
+ refresh_token?: string;
58
58
  /** Space-separated list of granted scopes */
59
59
  scope?: string;
60
60
  /** Token type (typically "Bearer") */
@@ -189,6 +189,8 @@ export type FigmaUser = User;
189
189
  * Keyed by projectId:environmentName
190
190
  */
191
191
  export type BootstrapData = {
192
+ /** Regional Content API base URL. Absent in entries cached before bootstrap returned it. */
193
+ contentApiUrl?: string;
192
194
  contentSystemId: string;
193
195
  oauthClientId: string;
194
196
  oauthClientSecret: string;
@@ -84,6 +84,9 @@ import { maskToken } from '../utils/token-display.js';
84
84
  ];
85
85
  for (const env of info.environments){
86
86
  lines.push(` ${pc.bold(env.name)}`, ` Tenant ID (contentSystemId): ${env.contentSystemId}`, ` Tenant Instance ID: ${env.tenantInstanceId}`);
87
+ if (env.contentApiUrl) {
88
+ lines.push(` Content API URL: ${env.contentApiUrl}`);
89
+ }
87
90
  }
88
91
  p.note(lines.join('\n'), 'Bootstrap Info');
89
92
  }
@@ -11,7 +11,7 @@ import { getTokenStore } from '../auth/token-store.js';
11
11
  import { getInfraEnvironment, getProjectNotFoundMessage } from '../constants.js';
12
12
  import { writeAgentConfigFiles } from '../lib/write-agent-config.js';
13
13
  import { ensureGitignore } from '../utils/config.js';
14
- import { addOrUpdateEnvVar } from '../utils/env-management.js';
14
+ import { addOrUpdateEnvVar, commentOutEnvVar, removeEnvVar } from '../utils/env-management.js';
15
15
  import { isDebug } from '../utils/is-debug.js';
16
16
  import { applyLambdaModifications } from '../utils/lambda-config.js';
17
17
  import * as log from '../utils/log.js';
@@ -29,6 +29,52 @@ import { writeProjectConfiguration } from './write-project-configuration.js';
29
29
  import { cacheAllEnvironments } from '../utils/cache-bootstrap.js';
30
30
  import { DEFAULT_TEMPLATE_SOURCE } from '../utils/download-template.js';
31
31
  import { parseTemplateSpec, TemplateSpecParseError } from '../utils/parse-template-spec.js';
32
+ import { ensurePayloadSecret } from '../utils/payload-secret.js';
33
+ async function removePayloadSecretFromEnv(projectDir) {
34
+ // New-project flow: the scaffold owns .env, so any PAYLOAD_SECRET carried
35
+ // over from a template is not a value the developer set. Remove it
36
+ // outright to keep the scaffolded file clean.
37
+ const removed = await removeEnvVar(projectDir, 'PAYLOAD_SECRET');
38
+ if (!removed) {
39
+ return;
40
+ }
41
+ p.log.warn(pc.yellow('⚠ Removed PAYLOAD_SECRET from .env. The Figma platform owns this value; a local ' + 'copy would silently diverge from the deployed secret and cause encrypted data ' + '(API keys, auth tokens) to fail decryption in production.'));
42
+ }
43
+ async function commentOutPayloadSecretInEnv(projectDir) {
44
+ // Existing-project flow: the developer's .env may hold a PAYLOAD_SECRET
45
+ // they need for another system or environment. Comment out rather than
46
+ // delete so the value survives and they can uncomment / relocate it.
47
+ const changed = await commentOutEnvVar(projectDir, 'PAYLOAD_SECRET', 'disabled by @payloadcms/figma: platform owns PAYLOAD_SECRET');
48
+ if (!changed) {
49
+ return;
50
+ }
51
+ p.log.warn(pc.yellow('⚠ Commented out PAYLOAD_SECRET in .env. The Figma platform owns this value; a ' + 'local copy would silently diverge from the deployed secret and cause encrypted ' + 'data (API keys, auth tokens) to fail decryption in production.'));
52
+ }
53
+ async function maybeEnsurePayloadSecret(args) {
54
+ if (!args.credential || !args.resolvedEnv) {
55
+ return false;
56
+ }
57
+ try {
58
+ await ensurePayloadSecret({
59
+ credential: args.credential,
60
+ projectInfo: {
61
+ environmentName: args.resolvedEnv.name,
62
+ projectId: args.cmsResourceId
63
+ },
64
+ tenantInstanceId: args.resolvedEnv.tenantInstanceId,
65
+ tokenStore: args.tokenStore,
66
+ // Re-init is the explicit recovery path after platform secret rotation.
67
+ refresh: true
68
+ });
69
+ log.debug('PAYLOAD_SECRET cached in TokenStore');
70
+ return true;
71
+ } catch (err) {
72
+ // Preserve the existing cache and .env fallback until a refresh succeeds.
73
+ const message = err instanceof Error ? err.message : 'Unknown error';
74
+ p.log.warn(pc.yellow(`⚠ Could not fetch PAYLOAD_SECRET (${message}). Existing secrets were preserved. Re-run init to retry.`));
75
+ return false;
76
+ }
77
+ }
32
78
  async function maybeWriteAgentConfigFiles(args) {
33
79
  if (args.noAgent) {
34
80
  return;
@@ -299,6 +345,12 @@ async function maybeWriteAgentConfigFiles(args) {
299
345
  p.log.error(error instanceof Error ? error.message : 'Failed to configure project');
300
346
  process.exit(1);
301
347
  }
348
+ await maybeEnsurePayloadSecret({
349
+ cmsResourceId,
350
+ credential,
351
+ resolvedEnv,
352
+ tokenStore
353
+ });
302
354
  p.outro(pc.green('✓ Vite project initialized successfully!'));
303
355
  return;
304
356
  }
@@ -374,6 +426,15 @@ async function maybeWriteAgentConfigFiles(args) {
374
426
  } catch (error) {
375
427
  p.log.warn(pc.yellow(`⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`));
376
428
  }
429
+ const secretCached = await maybeEnsurePayloadSecret({
430
+ cmsResourceId,
431
+ credential,
432
+ resolvedEnv,
433
+ tokenStore
434
+ });
435
+ if (secretCached) {
436
+ await commentOutPayloadSecretInEnv(process.cwd());
437
+ }
377
438
  } else {
378
439
  p.log.warn(pc.yellow('⚠ Payload was not detected in this project'));
379
440
  p.note('Run this command in a directory without an existing project or in an existing Payload project.', 'Action Required');
@@ -466,6 +527,15 @@ async function maybeWriteAgentConfigFiles(args) {
466
527
  } catch (error) {
467
528
  p.log.warn(pc.yellow(`⚠ Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`));
468
529
  }
530
+ const secretCached = await maybeEnsurePayloadSecret({
531
+ cmsResourceId,
532
+ credential,
533
+ resolvedEnv,
534
+ tokenStore
535
+ });
536
+ if (secretCached) {
537
+ await removePayloadSecretFromEnv(fullPath);
538
+ }
469
539
  // npm leaves node_modules in a transient state after a sequence of
470
540
  // add/remove calls; a final install reconciles it so the project is
471
541
  // immediately buildable.
@@ -8,12 +8,13 @@ import { getBootstrapInfo, getCmsResourceId } from '../api/control-plane.js';
8
8
  import { getValidCredential } from '../auth/oauth-flow.js';
9
9
  import { getTokenStore } from '../auth/token-store.js';
10
10
  import { cacheAllEnvironments } from '../utils/cache-bootstrap.js';
11
- import { addOrUpdateEnvVar, getEnvVar, removeEnvVar } from '../utils/env-management.js';
11
+ import { addOrUpdateEnvVar, commentOutEnvVar, getEnvVar, removeEnvVar } from '../utils/env-management.js';
12
12
  import { formatFile } from '../utils/formatter.js';
13
13
  import { getPackageManager } from '../utils/package-manager.js';
14
14
  import { removeFigmaContentSystemId } from '../utils/payload-config-ast.js';
15
15
  import { findPayloadConfig } from '../utils/payload-config-finder.js';
16
16
  import { checkPackageInstalled, installPackage } from '../utils/payload-package-check.js';
17
+ import { ensurePayloadSecret } from '../utils/payload-secret.js';
17
18
  import { getOwnVersion } from '../utils/version-check.js';
18
19
  export async function upgradeCommand(options = {}) {
19
20
  const cwd = process.cwd();
@@ -45,6 +46,11 @@ export async function upgradeCommand(options = {}) {
45
46
  isDryRun,
46
47
  warnings
47
48
  });
49
+ await migrateCommentOutPayloadSecret({
50
+ changes,
51
+ cwd,
52
+ isDryRun
53
+ });
48
54
  await migrateConfigAst({
49
55
  changes,
50
56
  cwd,
@@ -221,6 +227,64 @@ async function migrateRemoveDeprecatedEnvVars({ changes, cwd, isDryRun, warnings
221
227
  p.log.warning(`Deprecated env var removal failed: ${msg}`);
222
228
  }
223
229
  }
230
+ async function migrateCommentOutPayloadSecret({ changes, cwd, isDryRun }) {
231
+ try {
232
+ // Only touch active (uncommented) assignments — commentOutEnvVar already
233
+ // no-ops on commented lines, but checking here avoids the dry-run message
234
+ // when there's nothing left to do.
235
+ const existing = await getEnvVar(cwd, 'PAYLOAD_SECRET');
236
+ if (existing === null) {
237
+ return;
238
+ }
239
+ if (isDryRun) {
240
+ p.log.message(`${pc.dim('○')} Would comment out PAYLOAD_SECRET in .env after caching the platform secret`);
241
+ changes.push('Comment out PAYLOAD_SECRET in .env');
242
+ return;
243
+ }
244
+ const projectId = await getEnvVar(cwd, 'FIGMA_PROJECT_ID');
245
+ const environmentName = await getEnvVar(cwd, 'FIGMA_ENVIRONMENT_NAME');
246
+ if (!projectId || !environmentName) {
247
+ p.log.warning('Keeping PAYLOAD_SECRET in .env: initialize the project before migrating its secret.');
248
+ return;
249
+ }
250
+ const store = getTokenStore();
251
+ const credential = await getValidCredential(store);
252
+ if (!credential) {
253
+ p.log.warning('Keeping PAYLOAD_SECRET in .env: run `npx @payloadcms/figma login` and retry upgrade.');
254
+ return;
255
+ }
256
+ let bootstrapData = store.getBootstrapData(projectId, environmentName);
257
+ if (!bootstrapData) {
258
+ const bootstrapInfo = await getBootstrapInfo(credential, projectId);
259
+ cacheAllEnvironments(store, projectId, bootstrapInfo);
260
+ bootstrapData = store.getBootstrapData(projectId, environmentName);
261
+ }
262
+ if (!bootstrapData?.tenantInstanceId) {
263
+ p.log.warning('Keeping PAYLOAD_SECRET in .env: the project environment could not be resolved.');
264
+ return;
265
+ }
266
+ await ensurePayloadSecret({
267
+ credential,
268
+ projectInfo: {
269
+ environmentName,
270
+ projectId
271
+ },
272
+ refresh: true,
273
+ tenantInstanceId: bootstrapData.tenantInstanceId,
274
+ tokenStore: store
275
+ });
276
+ const changed = await commentOutEnvVar(cwd, 'PAYLOAD_SECRET', 'disabled by @payloadcms/figma: platform owns PAYLOAD_SECRET');
277
+ if (!changed) {
278
+ p.log.warning('Could not comment out PAYLOAD_SECRET in .env; the platform secret is cached. Retry upgrade.');
279
+ return;
280
+ }
281
+ p.log.message(`${pc.green('●')} Env: Commented out PAYLOAD_SECRET (Figma platform owns this value; ` + `a local copy would silently diverge from the deployed secret)`);
282
+ changes.push('Commented out PAYLOAD_SECRET in .env');
283
+ } catch (error) {
284
+ const msg = error instanceof Error ? error.message : 'Unknown error';
285
+ p.log.warning(`PAYLOAD_SECRET migration failed; keeping the existing .env value: ${msg}`);
286
+ }
287
+ }
224
288
  async function migrateConfigAst({ changes, cwd, isDryRun }) {
225
289
  try {
226
290
  const configPath = await findPayloadConfig(cwd);
@@ -4,7 +4,6 @@ import { getBootstrapInfo } from '../api/control-plane.js';
4
4
  import { tryGetCredential } from '../auth/oauth-flow.js';
5
5
  import { getValidProjectToken } from '../auth/project-token.js';
6
6
  import { getTokenStore } from '../auth/token-store.js';
7
- import { getEnvConfig } from '../constants.js';
8
7
  import { buildDocumentSchema } from '../db-content-api/utilities/schema/buildDocumentSchema.js';
9
8
  import { cacheAllEnvironments } from '../utils/cache-bootstrap.js';
10
9
  import { getEnvVar } from '../utils/env-management.js';
@@ -58,10 +57,10 @@ import { loginCommand } from './login.js';
58
57
  if (!apiKey && !projectToken) {
59
58
  throw new Error('Could not get a project token. Run `@payloadcms/figma login` and retry.');
60
59
  }
61
- // --infra-env is applied by the CLI before this fallback selects the Content API URL.
62
- const contentApiUrl = process.env.FIGMA_CONTENT_API_URL || getEnvConfig().contentApiUrl;
60
+ // The bootstrap environment carries its regional Content API URL.
61
+ const contentApiUrl = process.env.FIGMA_CONTENT_API_URL || environment.contentApiUrl;
63
62
  if (!contentApiUrl) {
64
- throw new Error('FIGMA_CONTENT_API_URL is required for this infrastructure environment.');
63
+ throw new Error(`No Content API URL returned for environment "${environment.name}".`);
65
64
  }
66
65
  const response = await fetch(`${contentApiUrl}/api/v0/content_systems/${encodeURIComponent(environment.contentSystemId)}/jsonb_to_index_migration_schema`, {
67
66
  body: JSON.stringify({
@@ -28,7 +28,12 @@ export const DEFAULT_CALLBACK_PORT = DEFAULT_CALLBACK_PORTS[0];
28
28
  redirectUri: process.env.FIGMA_REDIRECT_URI || `http://localhost:${DEFAULT_CALLBACK_PORT}/callback`,
29
29
  refreshUrl: `${apiBaseUrl}/v1/oauth/refresh`,
30
30
  scopes: [
31
- 'current_user:read'
31
+ 'current_user:read',
32
+ 'cloud:read',
33
+ 'cloud:create',
34
+ 'cloud:secrets:read',
35
+ 'cloud:content:read_write',
36
+ 'cloud:deploy'
32
37
  ],
33
38
  tokenUrl: `${apiBaseUrl}/v1/oauth/token`
34
39
  };
@@ -11,8 +11,6 @@ type EnvironmentConfig = {
11
11
  authorizationUrl: string;
12
12
  /** OAuth client ID. Override: FIGMA_CLIENT_ID or FIGMA_OAUTH_CLIENT_ID */
13
13
  clientId: string;
14
- /** Content API base URL. Override: FIGMA_CONTENT_API_URL */
15
- contentApiUrl: string;
16
14
  /** OIDC discovery endpoint */
17
15
  identityMetadata: string;
18
16
  /** JSON Web Key Set URL for token validation */
package/dist/constants.js CHANGED
@@ -7,7 +7,6 @@ import { getEnvVarSync } from './utils/env-management.js';
7
7
  apiBaseUrl: 'https://api.figma.com',
8
8
  authorizationUrl: 'https://www.figma.com/oauth',
9
9
  clientId: 'lelKVTAzOekFnirnlAMbuD',
10
- contentApiUrl: 'https://us-east-1.cms-tenants-001-production.figmacontent.com',
11
10
  identityMetadata: 'https://www.figma.com/.well-known/openid-configuration',
12
11
  jwksUri: 'https://static.figmacontent.com/.well_known/jwks.json'
13
12
  },
@@ -15,7 +14,6 @@ import { getEnvVarSync } from './utils/env-management.js';
15
14
  apiBaseUrl: 'https://api.staging.figma.com',
16
15
  authorizationUrl: 'https://staging.figma.com/oauth',
17
16
  clientId: 'wqAToBAp4UI9AZ5M6wTfT9',
18
- contentApiUrl: 'https://us-east-1.cms-tenants-001-staging.figmacontentstaging.com',
19
17
  identityMetadata: 'https://staging.figma.com/.well-known/openid-configuration',
20
18
  jwksUri: 'https://static.figmacontentstaging.com/.well_known/jwks.json'
21
19
  },
@@ -26,7 +24,6 @@ import { getEnvVarSync } from './utils/env-management.js';
26
24
  apiBaseUrl: '',
27
25
  authorizationUrl: '',
28
26
  clientId: 'rNZBcf3xBDmI76mQ9603su',
29
- contentApiUrl: '',
30
27
  identityMetadata: '',
31
28
  jwksUri: ''
32
29
  }
@@ -208,6 +208,12 @@ export function dataFromContentAPI(payload, collectionSlug, data, locale) {
208
208
  };
209
209
  return;
210
210
  }
211
+ // Document reads may omit an empty has-many select, while version writes store it as [].
212
+ // Return the same shape to Payload from both paths.
213
+ if (field.type === 'select' && field.hasMany && !isLocalized && value == null) {
214
+ current[fieldName] = [];
215
+ return;
216
+ }
211
217
  // Content API may omit fields; Payload expects null for optional fields.
212
218
  // In all-locales mode, localized fields use {} so afterRead can safely iterate locale keys.
213
219
  if (value === undefined) {
@@ -29,11 +29,11 @@ export function buildDocumentSchema(config) {
29
29
  };
30
30
  const collections = {};
31
31
  for (const collection of config.collections ?? []){
32
- collections[collection.slug] = buildCollectionSchema(collection.slug, collection.fields, blockRegistry);
32
+ collections[collection.slug] = buildCollectionSchema(collection.slug, collection.fields, blockRegistry, collection.indexes ?? []);
33
33
  }
34
34
  for (const global of config.globals ?? []){
35
35
  const slug = `_global-${global.slug}`;
36
- collections[slug] = buildCollectionSchema(slug, global.fields, blockRegistry);
36
+ collections[slug] = buildCollectionSchema(slug, global.fields, blockRegistry, []);
37
37
  }
38
38
  return {
39
39
  blocks: blockRegistry.blocksById,
@@ -41,7 +41,7 @@ export function buildDocumentSchema(config) {
41
41
  version: 1
42
42
  };
43
43
  }
44
- function buildCollectionSchema(name, fields, blockRegistry) {
44
+ function buildCollectionSchema(name, fields, blockRegistry, indexes) {
45
45
  const paths = {};
46
46
  collectPaths(fields, paths, {
47
47
  blockRegistry,
@@ -59,9 +59,14 @@ function buildCollectionSchema(name, fields, blockRegistry) {
59
59
  localized: false
60
60
  };
61
61
  }
62
+ // Field-level unique flags cannot express Payload's compound collection indexes.
63
+ const hints = indexes.filter((index)=>index.unique).map((index)=>({
64
+ type: 'unique',
65
+ paths: index.fields
66
+ }));
62
67
  return {
63
68
  name,
64
- hints: [],
69
+ hints,
65
70
  paths
66
71
  };
67
72
  }