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

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 (38) hide show
  1. package/dist/api/control-plane.d.ts +9 -0
  2. package/dist/api/control-plane.js +25 -0
  3. package/dist/auth/token-store.d.ts +16 -0
  4. package/dist/auth/token-store.js +33 -0
  5. package/dist/commands/init.js +71 -1
  6. package/dist/commands/upgrade.js +65 -1
  7. package/dist/db-content-api/utilities/data/index.js +6 -0
  8. package/dist/db-content-api/utilities/schema/buildDocumentSchema.js +9 -4
  9. package/dist/plugin/build-config.d.ts +9 -1
  10. package/dist/plugin/build-config.js +86 -5
  11. package/dist/plugin/cloud-limits/CloudLimitModal/index.d.ts +2 -1
  12. package/dist/plugin/cloud-limits/icons/ExternalLinkIcon.d.ts +2 -1
  13. package/dist/storage-content-api/api-types.d.ts +3 -0
  14. package/dist/storage-content-api/buildBaseMediaResponseHeaders.d.ts +1 -0
  15. package/dist/storage-content-api/buildBaseMediaResponseHeaders.js +8 -0
  16. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.d.ts +12 -0
  17. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.js +26 -0
  18. package/dist/storage-content-api/buildMediaRequestHeaders.d.ts +1 -0
  19. package/dist/storage-content-api/buildMediaRequestHeaders.js +14 -0
  20. package/dist/storage-content-api/buildMediaResponseHeaders.d.ts +4 -0
  21. package/dist/storage-content-api/buildMediaResponseHeaders.js +52 -0
  22. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.d.ts +3 -3
  23. package/dist/storage-content-api/getDownloadResponseHeaderPolicy.js +10 -4
  24. package/dist/storage-content-api/getMediaType.d.ts +1 -0
  25. package/dist/storage-content-api/getMediaType.js +3 -0
  26. package/dist/storage-content-api/hasSupportedContentEncoding.d.ts +1 -0
  27. package/dist/storage-content-api/hasSupportedContentEncoding.js +6 -0
  28. package/dist/storage-content-api/mediaErrorResponse.d.ts +1 -0
  29. package/dist/storage-content-api/mediaErrorResponse.js +12 -0
  30. package/dist/storage-content-api/shouldAttachMedia.d.ts +1 -0
  31. package/dist/storage-content-api/shouldAttachMedia.js +34 -0
  32. package/dist/storage-content-api/staticHandler.js +91 -24
  33. package/dist/utils/env-management.d.ts +15 -0
  34. package/dist/utils/env-management.js +47 -0
  35. package/dist/utils/payload-config-ast.js +5 -2
  36. package/dist/utils/payload-secret.d.ts +28 -0
  37. package/dist/utils/payload-secret.js +34 -0
  38. package/package.json +14 -12
@@ -155,6 +155,15 @@ export type BootstrapInfo = {
155
155
  * @param environmentName - Optional environment name filter
156
156
  */
157
157
  export declare function getBootstrapInfo(credential: AuthCredential, cmsResourceId: string, environmentName?: string): Promise<BootstrapInfo>;
158
+ /**
159
+ * Fetch the decrypted value of a tenant environment variable by name.
160
+ * Maps to: GET /v1/environments/:tenant_instance_id/environment_variables/by_name?name=...
161
+ *
162
+ * Only variables with `user_visibility: name_and_value` are returned; the
163
+ * endpoint answers 404 otherwise. Used by init and buildFigmaConfig to
164
+ * resolve PAYLOAD_SECRET on developer machines.
165
+ */
166
+ export declare function getEnvironmentVariableByName(credential: AuthCredential, tenantInstanceId: string, name: string): Promise<string>;
158
167
  /**
159
168
  * Resolve a CMS Resource ID from a legacy dataset (content system) ID.
160
169
  * Maps to: GET /v1/cms/dataset/:datasetId
@@ -287,6 +287,31 @@ import { controlPlaneFetch } from './control-plane-fetch.js';
287
287
  }
288
288
  };
289
289
  }
290
+ /**
291
+ * Fetch the decrypted value of a tenant environment variable by name.
292
+ * Maps to: GET /v1/environments/:tenant_instance_id/environment_variables/by_name?name=...
293
+ *
294
+ * Only variables with `user_visibility: name_and_value` are returned; the
295
+ * endpoint answers 404 otherwise. Used by init and buildFigmaConfig to
296
+ * resolve PAYLOAD_SECRET on developer machines.
297
+ */ export async function getEnvironmentVariableByName(credential, tenantInstanceId, name) {
298
+ const shouldMock = process.env.FIGMA_MOCK_CONTROL_PLANE === 'true';
299
+ if (shouldMock) {
300
+ log.debug('Using mock Control Plane API for getEnvironmentVariableByName (FIGMA_MOCK_CONTROL_PLANE === "true")');
301
+ return `mock-${name.toLowerCase()}-${tenantInstanceId}`;
302
+ }
303
+ const url = `${getControlPlaneBaseUrl()}/v1/environments/${encodeURIComponent(tenantInstanceId)}` + `/environment_variables/by_name?name=${encodeURIComponent(name)}`;
304
+ log.debug(`Calling getEnvironmentVariableByName API at ${url}`);
305
+ const response = await controlPlaneFetch({
306
+ context: `get environment variable ${name}`,
307
+ options: {
308
+ headers: getAuthHeaders(credential)
309
+ },
310
+ url
311
+ });
312
+ const data = await response.json();
313
+ return data.meta.value;
314
+ }
290
315
  /**
291
316
  * Resolve a CMS Resource ID from a legacy dataset (content system) ID.
292
317
  * Maps to: GET /v1/cms/dataset/:datasetId
@@ -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
@@ -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);
@@ -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
  }
@@ -13,7 +13,15 @@ export declare const FIGMA_INTERNAL_FORWARDED_HAS_AUTH_BYPASS_HEADER = "figma-in
13
13
  *
14
14
  * Differences from standard Payload Config:
15
15
  * - `db`: Omitted (auto-injected by Figma platform)
16
- * - `secret`: Omitted (auto-injected by Figma platform)
16
+ * - `secret`: Omitted. The platform owns `PAYLOAD_SECRET`. `init`'s AST
17
+ * modifier strips this line from the tenant's config, and this type
18
+ * doesn't accept it back in. `buildFigmaConfig` injects the value at
19
+ * runtime from `process.env.PAYLOAD_SECRET` (Lambda) or the encrypted
20
+ * TokenStore cache (local dev) — never written to `.env`.
21
+ * - `previousSecrets`: The plugin appends its own compatibility entry so
22
+ * data written under the old shared hosted secret keeps decrypting after
23
+ * the platform switched to per-tenant secrets; any tenant-supplied entries
24
+ * are preserved in order.
17
25
  * - `editor`: Optional (defaults to lexicalEditor() if not provided)
18
26
  * - `contentSystemId`: Optional (resolved automatically from env vars or bootstrap cache)
19
27
  *
@@ -2,7 +2,7 @@ import { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage';
2
2
  import { lexicalEditor } from '@payloadcms/richtext-lexical';
3
3
  import { buildConfig as payloadBuildConfig } from 'payload';
4
4
  import { deepMergeSimple } from 'payload/shared';
5
- import { getBootstrapInfo } from '../api/control-plane.js';
5
+ import { getBootstrapInfo, getEnvironmentVariableByName } from '../api/control-plane.js';
6
6
  import { getValidCredential } from '../auth/oauth-flow.js';
7
7
  import { getTokenStore } from '../auth/token-store.js';
8
8
  import { getEnvConfig } from '../constants.js';
@@ -16,7 +16,7 @@ import { createStorageClient } from '../storage-content-api/client.js';
16
16
  import { contentApiStorageAdapter } from '../storage-content-api/index.js';
17
17
  import { translations as figmaTranslations } from '../translations/index.js';
18
18
  import { cacheAllEnvironments } from '../utils/cache-bootstrap.js';
19
- import { getEnvVarSync } from '../utils/env-management.js';
19
+ import { getEnvVarSync, getParsedEnvVarSync } from '../utils/env-management.js';
20
20
  import * as log from '../utils/log.js';
21
21
  import { logMissingCliAuth } from './auth-preflight.js';
22
22
  import { logMissingContentSystemId } from './bootstrap-preflight.js';
@@ -170,6 +170,49 @@ function missingOAuthCredential(name) {
170
170
  function messageOf(error) {
171
171
  return error instanceof Error ? error.message : 'Unknown error';
172
172
  }
173
+ /**
174
+ * Local-dev fallback: if the tenant config didn't supply a secret (usually
175
+ * because process.env.PAYLOAD_SECRET is unset), try the TokenStore cache,
176
+ * then fetch from the Control Plane. Skipped in Lambda — the platform
177
+ * injects PAYLOAD_SECRET as an env var there, and TokenStore throws in AWS.
178
+ * Returns undefined if we can't resolve one; the caller lets payload.init()
179
+ * throw its own error.
180
+ */ async function resolvePayloadSecretForRuntime(store, projectId, environmentName, tenantInstanceId) {
181
+ const cached = store.getPayloadSecret({
182
+ projectInfo: {
183
+ environmentName,
184
+ projectId
185
+ }
186
+ });
187
+ if (cached) {
188
+ return cached;
189
+ }
190
+ let credential;
191
+ try {
192
+ credential = await getValidCredential(store);
193
+ } catch (error) {
194
+ log.debug(`PAYLOAD_SECRET fetch skipped: ${messageOf(error)}`);
195
+ return undefined;
196
+ }
197
+ if (!credential) {
198
+ log.debug('PAYLOAD_SECRET fetch skipped: no cached CLI credential');
199
+ return undefined;
200
+ }
201
+ try {
202
+ const secret = await getEnvironmentVariableByName(credential, tenantInstanceId, 'PAYLOAD_SECRET');
203
+ store.setPayloadSecret({
204
+ projectInfo: {
205
+ environmentName,
206
+ projectId
207
+ },
208
+ secret
209
+ });
210
+ return secret;
211
+ } catch (error) {
212
+ log.debug(`PAYLOAD_SECRET fetch failed: ${messageOf(error)}`);
213
+ return undefined;
214
+ }
215
+ }
173
216
  /**
174
217
  * Creates storage configuration for upload collections
175
218
  */ function createStorageConfig(url, contentSystemId, uploadInstructionsAccess) {
@@ -325,7 +368,30 @@ export async function buildFigmaConfig(config) {
325
368
  }
326
369
  const userJobsAccessRun = config.jobs?.access?.run;
327
370
  const adminCollectionSlug = getAdminCollectionSlug(config);
328
- // Build complete config with Figma platform defaults
371
+ // Lambda: env var is authoritative (TokenStore unusable in AWS). Local:
372
+ // TokenStore first so a leftover .env value can't shadow the platform
373
+ // secret; env var is only a last-resort fallback.
374
+ let resolvedSecret;
375
+ if (process.env.AWS_EXECUTION_ENV) {
376
+ resolvedSecret = process.env.PAYLOAD_SECRET;
377
+ } else {
378
+ const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
379
+ const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
380
+ if (projectId && environmentName && environmentId) {
381
+ resolvedSecret = await resolvePayloadSecretForRuntime(getTokenStore(), projectId, environmentName, environmentId);
382
+ }
383
+ if (!resolvedSecret) {
384
+ // Config may be evaluated before the framework loads dotenv. Parse the
385
+ // file without mutating process.env, preserving quotes/comments correctly.
386
+ resolvedSecret = process.env.PAYLOAD_SECRET || getParsedEnvVarSync(process.cwd(), 'PAYLOAD_SECRET') || undefined;
387
+ if (resolvedSecret) {
388
+ log.warning('Using a local PAYLOAD_SECRET fallback because the platform secret could not be resolved. ' + 'It may differ from the deployed secret. Run `npx @payloadcms/figma init --id <project-id> --force` to refresh it.');
389
+ }
390
+ }
391
+ }
392
+ // Build complete config with Figma platform defaults.
393
+ // `secret` may be undefined here; payload.init() enforces its presence at
394
+ // runtime, so we relax the intermediate type instead of forging a default.
329
395
  const configWithFigmaDefaults = {
330
396
  ...config,
331
397
  admin: {
@@ -367,6 +433,7 @@ export async function buildFigmaConfig(config) {
367
433
  ...config.i18n,
368
434
  translations: deepMergeSimple(figmaTranslations, config.i18n?.translations ?? {})
369
435
  },
436
+ secret: resolvedSecret,
370
437
  // Gate /api/payload-jobs/run and /api/payload-jobs/handle-schedules. Honor the
371
438
  // sites-worker trust marker so Figma infra job runs never break, defer to the
372
439
  // tenant's jobs.access.run if they set one, otherwise require an authenticated
@@ -386,14 +453,28 @@ export async function buildFigmaConfig(config) {
386
453
  // explicit view, and other unrecognized values.
387
454
  return Boolean(args.req.user) && passesMakeViewerWriteGate(args.req.user);
388
455
  }
389
- }
456
+ },
457
+ // Remove Payload's default read/write denials so the jobs collection uses
458
+ // the standard access defaults and baseAccess Make-permission write gate.
459
+ // Preserve tenant-supplied overrides; jobs.access.run separately controls
460
+ // the job execution endpoints.
461
+ jobsCollectionOverrides: config.jobs?.jobsCollectionOverrides ?? (({ defaultJobsCollection })=>{
462
+ const { access: _access, ...rest } = defaultJobsCollection;
463
+ return rest;
464
+ })
390
465
  },
391
466
  ...isProduction && !config.logger ? {
392
467
  logger: {
393
468
  options: {}
394
469
  }
395
470
  } : {},
396
- secret: 'MY_SECRET',
471
+ // The platform owns rotation of PAYLOAD_SECRET; this compat entry lets
472
+ // data encrypted under the old shared hosted secret keep decrypting.
473
+ // Appended last so any tenant-supplied previousSecrets are honored first.
474
+ previousSecrets: [
475
+ ...config.previousSecrets ?? [],
476
+ Buffer.from('TVlfU0VDUkVU', 'base64').toString('utf8')
477
+ ],
397
478
  // Add oauth to plugins if not already present
398
479
  plugins: [
399
480
  ...config.plugins ?? [],
@@ -1,8 +1,9 @@
1
+ import type { ReactElement } from 'react';
1
2
  import './index.scss';
2
3
  type Props = {
3
4
  collectionLabel?: string;
4
5
  collectionListURL?: string;
5
6
  onRetry: () => void;
6
7
  };
7
- export declare function FigmaCloudLimitDocumentCountModal({ collectionLabel, collectionListURL, onRetry, }: Props): import("react").JSX.Element;
8
+ export declare function FigmaCloudLimitDocumentCountModal({ collectionLabel, collectionListURL, onRetry, }: Props): ReactElement;
8
9
  export {};
@@ -1,2 +1,3 @@
1
+ import type { ReactElement } from 'react';
1
2
  /** External link icon (box with arrow pointing out). Used in cloud-limit UI. */
2
- export declare function ExternalLinkIcon(): import("react").JSX.Element;
3
+ export declare function ExternalLinkIcon(): ReactElement;
@@ -45,6 +45,9 @@ export type UploadPaths = {
45
45
  collectionId: string;
46
46
  expiresIn: number;
47
47
  filename: string;
48
+ responseHeaders: {
49
+ cacheControl: string;
50
+ };
48
51
  };
49
52
  };
50
53
  };
@@ -0,0 +1 @@
1
+ export declare function buildBaseMediaResponseHeaders(): Headers;
@@ -0,0 +1,8 @@
1
+ export function buildBaseMediaResponseHeaders() {
2
+ return new Headers({
3
+ 'Accept-Ranges': 'bytes',
4
+ 'Cache-Control': 'private, no-store',
5
+ Vary: 'Cookie',
6
+ 'X-Content-Type-Options': 'nosniff'
7
+ });
8
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * After a client upload, Payload reads the file from storage to determine image dimensions.
3
+ * For types outside the inline allowlist, such as SVG (which can contain scripts), omit
4
+ * Content-Type so Payload uses the original upload MIME type instead of application/octet-stream.
5
+ * Attachment and sandbox protections remain. This helper is only used when uploadReference
6
+ * is present; normal file requests use buildMediaResponseHeaders.
7
+ */
8
+ export declare function buildClientUploadFetchBackHeaders({ fallbackContentType, filename, upstreamHeaders, }: {
9
+ fallbackContentType: string | undefined;
10
+ filename: string;
11
+ upstreamHeaders: Headers;
12
+ }): Headers;
@@ -0,0 +1,26 @@
1
+ import { buildMediaResponseHeaders } from './buildMediaResponseHeaders.js';
2
+ import { shouldAttachMedia } from './shouldAttachMedia.js';
3
+ /**
4
+ * After a client upload, Payload reads the file from storage to determine image dimensions.
5
+ * For types outside the inline allowlist, such as SVG (which can contain scripts), omit
6
+ * Content-Type so Payload uses the original upload MIME type instead of application/octet-stream.
7
+ * Attachment and sandbox protections remain. This helper is only used when uploadReference
8
+ * is present; normal file requests use buildMediaResponseHeaders.
9
+ */ export function buildClientUploadFetchBackHeaders({ fallbackContentType, filename, upstreamHeaders }) {
10
+ const effectiveContentType = upstreamHeaders.get('Content-Type') || fallbackContentType;
11
+ const upstreamHeadersWithFallback = new Headers(upstreamHeaders);
12
+ if (effectiveContentType) {
13
+ upstreamHeadersWithFallback.set('Content-Type', effectiveContentType);
14
+ }
15
+ const headers = buildMediaResponseHeaders({
16
+ filename,
17
+ upstreamHeaders: upstreamHeadersWithFallback
18
+ });
19
+ if (effectiveContentType && shouldAttachMedia(upstreamHeadersWithFallback)) {
20
+ // Payload uses the response content type when processing an uploaded image.
21
+ // The sanitized type can hide the original upload MIME type.
22
+ // Remove it so Payload falls back to the original type.
23
+ headers.delete('Content-Type');
24
+ }
25
+ return headers;
26
+ }
@@ -0,0 +1 @@
1
+ export declare function buildMediaRequestHeaders(incomingHeaders: Headers): Headers;
@@ -0,0 +1,14 @@
1
+ export function buildMediaRequestHeaders(incomingHeaders) {
2
+ const headers = new Headers({
3
+ 'Accept-Encoding': 'identity'
4
+ });
5
+ const range = incomingHeaders.get('Range');
6
+ if (range) {
7
+ headers.set('Range', range);
8
+ const ifRange = incomingHeaders.get('If-Range');
9
+ if (ifRange) {
10
+ headers.set('If-Range', ifRange);
11
+ }
12
+ }
13
+ return headers;
14
+ }
@@ -0,0 +1,4 @@
1
+ export declare function buildMediaResponseHeaders({ filename, upstreamHeaders, }: {
2
+ filename: string;
3
+ upstreamHeaders: Headers;
4
+ }): Headers;
@@ -0,0 +1,52 @@
1
+ import { buildBaseMediaResponseHeaders } from './buildBaseMediaResponseHeaders.js';
2
+ import { getMediaType } from './getMediaType.js';
3
+ import { shouldAttachMedia } from './shouldAttachMedia.js';
4
+ const FORWARDED_MEDIA_RESPONSE_HEADERS = [
5
+ 'Cache-Control',
6
+ 'Content-Length',
7
+ 'Content-Range',
8
+ 'ETag',
9
+ 'Last-Modified'
10
+ ];
11
+ const ATTACHMENT_CSP = "sandbox; default-src 'none'; base-uri 'none'; form-action 'none'";
12
+ export function buildMediaResponseHeaders({ filename, upstreamHeaders }) {
13
+ const headers = buildBaseMediaResponseHeaders();
14
+ for (const name of FORWARDED_MEDIA_RESPONSE_HEADERS){
15
+ const value = upstreamHeaders.get(name);
16
+ if (value) {
17
+ headers.set(name, value);
18
+ }
19
+ }
20
+ if (shouldAttachMedia(upstreamHeaders)) {
21
+ headers.set('Content-Type', 'application/octet-stream');
22
+ headers.set('Content-Disposition', attachmentDisposition(filename));
23
+ headers.set('Content-Security-Policy', ATTACHMENT_CSP);
24
+ } else {
25
+ // Send only the approved media type; do not pass through untrusted parameters.
26
+ headers.set('Content-Type', getMediaType(upstreamHeaders));
27
+ }
28
+ return headers;
29
+ }
30
+ function attachmentDisposition(filename) {
31
+ const sanitizedName = sanitizeFilename(filename);
32
+ const safeName = Array.from(sanitizedName).slice(0, 255).join('') || 'download';
33
+ let utf8Name;
34
+ try {
35
+ // encodeURIComponent leaves !, ', (, ), and * unchanged. Encode those five characters as % escapes.
36
+ utf8Name = encodeURIComponent(safeName).replace(/[!'()*]/g, (character)=>`%${character.charCodeAt(0).toString(16).toUpperCase()}`);
37
+ } catch {
38
+ // Invalid UTF-16, such as an unpaired surrogate, cannot be encoded in filename*.
39
+ return `attachment; filename="download"; filename*=UTF-8''download`;
40
+ }
41
+ // Replace non-ASCII and control characters, quotes, backslashes, and % with underscores.
42
+ const asciiName = safeName.replace(/[^\x20-\x7e]/g, '_').replace(/["\\%]/g, '_');
43
+ return `attachment; filename="${asciiName}"; filename*=UTF-8''${utf8Name}`;
44
+ }
45
+ function sanitizeFilename(filename) {
46
+ // Replace control characters (0–31 and 127) and slashes with underscores.
47
+ // This keeps newlines and directory paths out of the download name.
48
+ return Array.from(filename, (character)=>{
49
+ const codePoint = character.codePointAt(0);
50
+ return codePoint < 32 || codePoint === 127 || character === '/' || character === '\\' ? '_' : character;
51
+ }).join('');
52
+ }
@@ -1,11 +1,11 @@
1
+ import type { Payload } from 'payload';
1
2
  export declare const DEFAULT_MEDIA_CACHE_CONTROL = "private, no-store";
2
3
  export declare const MAX_MEDIA_CACHE_CONTROL_LENGTH = 1024;
3
4
  type DownloadResponseHeaderPolicy = {
4
5
  cacheControl: string;
5
- hasIgnoredHeaders: boolean;
6
- rejectedCacheControlOverride: boolean;
7
6
  };
8
- export declare const getDownloadResponseHeaderPolicy: ({ responseHeaders, }: {
7
+ export declare const getDownloadResponseHeaderPolicy: ({ logger, responseHeaders, }: {
8
+ logger: Pick<Payload["logger"], "debug">;
9
9
  responseHeaders: Headers;
10
10
  }) => DownloadResponseHeaderPolicy;
11
11
  export {};
@@ -1,16 +1,22 @@
1
1
  export const DEFAULT_MEDIA_CACHE_CONTROL = 'private, no-store';
2
2
  export const MAX_MEDIA_CACHE_CONTROL_LENGTH = 1024;
3
3
  const PRINTABLE_ASCII_REGEX = /^[\x20-\x7e]+$/;
4
- export const getDownloadResponseHeaderPolicy = ({ responseHeaders })=>{
4
+ export const getDownloadResponseHeaderPolicy = ({ logger, responseHeaders })=>{
5
5
  const configuredCacheControl = responseHeaders.get('Cache-Control')?.trim();
6
6
  const isCacheControlValid = hasValidCacheControl(configuredCacheControl);
7
7
  const hasIgnoredHeaders = [
8
8
  ...responseHeaders.keys()
9
9
  ].some((name)=>name !== 'cache-control');
10
+ const rejectedCacheControlOverride = !isCacheControlValid;
11
+ if (hasIgnoredHeaders || rejectedCacheControlOverride) {
12
+ logger.debug({
13
+ hasIgnoredResponseHeaders: hasIgnoredHeaders,
14
+ msg: 'Filtered media response header overrides',
15
+ rejectedCacheControlOverride
16
+ });
17
+ }
10
18
  return {
11
- cacheControl: isCacheControlValid && configuredCacheControl ? configuredCacheControl : DEFAULT_MEDIA_CACHE_CONTROL,
12
- hasIgnoredHeaders,
13
- rejectedCacheControlOverride: !isCacheControlValid
19
+ cacheControl: isCacheControlValid && configuredCacheControl ? configuredCacheControl : DEFAULT_MEDIA_CACHE_CONTROL
14
20
  };
15
21
  };
16
22
  function hasValidCacheControl(cacheControl) {
@@ -0,0 +1 @@
1
+ export declare function getMediaType(headers: Headers): string;
@@ -0,0 +1,3 @@
1
+ export function getMediaType(headers) {
2
+ return headers.get('Content-Type')?.split(';', 1).at(0)?.trim().toLowerCase() || '';
3
+ }
@@ -0,0 +1 @@
1
+ export declare function hasSupportedContentEncoding(headers: Headers): boolean;
@@ -0,0 +1,6 @@
1
+ // Fetch can automatically decompress a file without updating its size or byte-range headers.
2
+ // Reject compressed responses so the headers still match the bytes we send.
3
+ export function hasSupportedContentEncoding(headers) {
4
+ const contentEncoding = headers.get('content-encoding')?.trim().toLowerCase();
5
+ return contentEncoding == null || contentEncoding === '' || contentEncoding === 'identity';
6
+ }
@@ -0,0 +1 @@
1
+ export declare function mediaErrorResponse(status: number, body: string, contentRange?: string): Response;
@@ -0,0 +1,12 @@
1
+ import { buildBaseMediaResponseHeaders } from './buildBaseMediaResponseHeaders.js';
2
+ export function mediaErrorResponse(status, body, contentRange) {
3
+ const headers = buildBaseMediaResponseHeaders();
4
+ headers.set('Content-Type', 'text/plain;charset=UTF-8');
5
+ if (contentRange) {
6
+ headers.set('Content-Range', contentRange);
7
+ }
8
+ return new Response(body, {
9
+ headers,
10
+ status
11
+ });
12
+ }
@@ -0,0 +1 @@
1
+ export declare function shouldAttachMedia(upstreamHeaders: Headers): boolean;
@@ -0,0 +1,34 @@
1
+ import { getMediaType } from './getMediaType.js';
2
+ // Only these media types may render inline on the application's origin.
3
+ // Unknown or active content must download as an attachment.
4
+ const INLINE_MEDIA_TYPES = new Set([
5
+ 'application/font-woff',
6
+ 'audio/aac',
7
+ 'audio/flac',
8
+ 'audio/mp4',
9
+ 'audio/mpeg',
10
+ 'audio/ogg',
11
+ 'audio/wav',
12
+ 'audio/webm',
13
+ 'font/otf',
14
+ 'font/ttf',
15
+ 'font/woff',
16
+ 'font/woff2',
17
+ 'image/avif',
18
+ 'image/bmp',
19
+ 'image/gif',
20
+ 'image/jpeg',
21
+ 'image/png',
22
+ 'image/vnd.microsoft.icon',
23
+ 'image/webp',
24
+ 'image/x-icon',
25
+ 'video/mp4',
26
+ 'video/mpeg',
27
+ 'video/ogg',
28
+ 'video/quicktime',
29
+ 'video/webm'
30
+ ]);
31
+ export function shouldAttachMedia(upstreamHeaders) {
32
+ const mediaType = getMediaType(upstreamHeaders);
33
+ return !mediaType || !INLINE_MEDIA_TYPES.has(mediaType);
34
+ }
@@ -1,10 +1,17 @@
1
1
  import { getFilePrefix } from '@payloadcms/plugin-cloud-storage/utilities';
2
2
  import path from 'path';
3
3
  import { isImage } from 'payload/shared';
4
+ import { buildClientUploadFetchBackHeaders } from './buildClientUploadFetchBackHeaders.js';
5
+ import { buildMediaRequestHeaders } from './buildMediaRequestHeaders.js';
6
+ import { buildMediaResponseHeaders } from './buildMediaResponseHeaders.js';
7
+ import { getDownloadResponseHeaderPolicy } from './getDownloadResponseHeaderPolicy.js';
8
+ import { hasSupportedContentEncoding } from './hasSupportedContentEncoding.js';
9
+ import { mediaErrorResponse } from './mediaErrorResponse.js';
10
+ import { resolveDownloadResponseHeaders } from './resolveDownloadResponseHeaders.js';
4
11
  import { parseUploadReference } from './utilities/index.js';
5
12
  const PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS = 300;
6
13
  export const getHandler = ({ client, collection })=>{
7
- return async (req, { params: { filename, uploadReference } })=>{
14
+ return async (req, { headers, params: { filename, uploadReference } })=>{
8
15
  try {
9
16
  const prefix = await getFilePrefix({
10
17
  collection,
@@ -13,11 +20,20 @@ export const getHandler = ({ client, collection })=>{
13
20
  uploadReference
14
21
  });
15
22
  const key = path.posix.join(prefix, filename);
23
+ const resolvedResponseHeaders = resolveDownloadResponseHeaders({
24
+ collection,
25
+ payloadResponseHeaders: headers
26
+ });
27
+ const responseHeaderPolicy = getDownloadResponseHeaderPolicy({
28
+ logger: req.payload.logger,
29
+ responseHeaders: resolvedResponseHeaders
30
+ });
16
31
  const { data, error } = await client.POST('/api/v0/uploads/download/sign', {
17
32
  body: {
18
33
  collectionId: collection.slug,
19
34
  expiresIn: PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS,
20
- filename: key
35
+ filename: key,
36
+ responseHeaders: responseHeaderPolicy
21
37
  }
22
38
  });
23
39
  if (error || !data) {
@@ -26,29 +42,58 @@ export const getHandler = ({ client, collection })=>{
26
42
  status: 500
27
43
  });
28
44
  }
29
- // On a client-upload fetch-back, core reads this response body into req.file.data to
30
- // size the image; a 302's empty body crashes getImageSize. Return real bytes for
31
- // images (and unknown mimetypes, to be safe), but keep the redirect otherwise so we
32
- // don't download large non-images server-side.
33
- if (uploadReference) {
34
- const { mimeType } = parseUploadReference(uploadReference);
35
- if (!mimeType || isImage(mimeType)) {
36
- const fileResponse = await fetch(data.url);
37
- if (!fileResponse.ok) {
38
- req.payload.logger.error(`Failed to fetch file for client-upload buffer fetch-back: ${fileResponse.status}`);
39
- return new Response('Internal Server Error', {
40
- status: 500
41
- });
42
- }
43
- const contentType = fileResponse.headers.get('Content-Type') ?? mimeType ?? 'application/octet-stream';
44
- return new Response(await fileResponse.arrayBuffer(), {
45
- headers: {
46
- 'Content-Type': contentType
47
- }
48
- });
49
- }
45
+ const isClientUpload = Boolean(uploadReference);
46
+ const clientUploadMimeType = isClientUpload ? parseUploadReference(uploadReference).mimeType : undefined;
47
+ // Lambda responses have a 6 MB limit, so redirect normal media to its signed storage URL.
48
+ // Post-upload image inspection still needs a response body from Payload.
49
+ if (shouldReturnRedirect({
50
+ clientUploadMimeType,
51
+ isClientUpload
52
+ })) {
53
+ return Response.redirect(data.url, 302);
54
+ }
55
+ const requestHeaders = buildMediaRequestHeaders(req.headers);
56
+ let fileResponse;
57
+ try {
58
+ fileResponse = await fetch(data.url, {
59
+ credentials: 'omit',
60
+ headers: requestHeaders,
61
+ redirect: 'manual',
62
+ referrerPolicy: 'no-referrer',
63
+ signal: req.signal
64
+ });
65
+ } catch {
66
+ // Fetch errors can contain the signed URL; log only a fixed message to avoid exposing it.
67
+ req.payload.logger.error('Failed to fetch file from storage');
68
+ return mediaErrorResponse(500, 'Internal Server Error');
69
+ }
70
+ if (fileResponse.status === 416 && requestHeaders.has('Range')) {
71
+ await cancelResponseBody(fileResponse);
72
+ return mediaErrorResponse(416, 'Range Not Satisfiable', fileResponse.headers.get('Content-Range') ?? undefined);
50
73
  }
51
- return Response.redirect(data.url, 302);
74
+ if (!fileResponse.ok) {
75
+ await cancelResponseBody(fileResponse);
76
+ req.payload.logger.error(`Failed to fetch file from storage: ${fileResponse.status}`);
77
+ return mediaErrorResponse(500, 'Internal Server Error');
78
+ }
79
+ if (!hasSupportedContentEncoding(fileResponse.headers)) {
80
+ await cancelResponseBody(fileResponse);
81
+ req.payload.logger.error('Unsupported Content-Encoding from storage');
82
+ return mediaErrorResponse(502, 'Bad Gateway');
83
+ }
84
+ const responseHeaders = isClientUpload ? buildClientUploadFetchBackHeaders({
85
+ fallbackContentType: clientUploadMimeType,
86
+ filename,
87
+ upstreamHeaders: fileResponse.headers
88
+ }) : buildMediaResponseHeaders({
89
+ filename,
90
+ upstreamHeaders: fileResponse.headers
91
+ });
92
+ return new Response(fileResponse.body, {
93
+ headers: responseHeaders,
94
+ status: fileResponse.status,
95
+ statusText: fileResponse.statusText
96
+ });
52
97
  } catch (err) {
53
98
  req.payload.logger.error({
54
99
  err,
@@ -60,3 +105,25 @@ export const getHandler = ({ client, collection })=>{
60
105
  }
61
106
  };
62
107
  };
108
+ function isRunningInLambda() {
109
+ return process.env.AWS_EXECUTION_ENV?.startsWith('AWS_Lambda_') === true;
110
+ }
111
+ // Stream all files outside Lambda. In Lambda, redirect normal requests and non-image uploads.
112
+ // Return image uploads directly so Payload can inspect their dimensions; do the same when
113
+ // the upload type is unknown, since it might be an image.
114
+ function shouldReturnRedirect({ clientUploadMimeType, isClientUpload }) {
115
+ if (!isRunningInLambda()) {
116
+ return false;
117
+ }
118
+ if (!isClientUpload) {
119
+ return true;
120
+ }
121
+ return Boolean(clientUploadMimeType && !isImage(clientUploadMimeType));
122
+ }
123
+ async function cancelResponseBody(response) {
124
+ try {
125
+ await response.body?.cancel();
126
+ } catch {
127
+ // The response will not be consumed after an error; cancellation is best-effort cleanup.
128
+ }
129
+ }
@@ -14,6 +14,8 @@ export declare function getEnvVar(projectPath: string, key: string): Promise<nul
14
14
  * @returns The value if found, null otherwise
15
15
  */
16
16
  export declare function getEnvVarSync(projectPath: string, key: string): null | string;
17
+ /** Read a dotenv-parsed value without populating process.env. */
18
+ export declare function getParsedEnvVarSync(projectPath: string, key: string): null | string;
17
19
  /**
18
20
  * Add or update an environment variable in .env file
19
21
  *
@@ -22,6 +24,19 @@ export declare function getEnvVarSync(projectPath: string, key: string): null |
22
24
  * @param value - Environment variable value
23
25
  */
24
26
  export declare function addOrUpdateEnvVar(projectPath: string, key: string, value: string): Promise<void>;
27
+ /**
28
+ * Comment out an environment variable in .env file by prepending `# ` to any
29
+ * assignment line for the given key. Preserves the value so the developer can
30
+ * uncomment it later (or move it to another env file). No-op if the key is
31
+ * absent or every occurrence is already commented.
32
+ *
33
+ * @param projectPath - Path to project directory
34
+ * @param key - Environment variable name to disable
35
+ * @param annotation - Optional trailing comment appended to each disabled
36
+ * line, so the developer knows why it was disabled
37
+ * @returns true if at least one line was commented out, false otherwise
38
+ */
39
+ export declare function commentOutEnvVar(projectPath: string, key: string, annotation?: string): Promise<boolean>;
25
40
  /**
26
41
  * Remove an environment variable from .env file
27
42
  *
@@ -1,3 +1,4 @@
1
+ import { parse } from 'dotenv';
1
2
  import fs from 'fs/promises';
2
3
  import fsSync from 'node:fs';
3
4
  import path from 'path';
@@ -54,6 +55,14 @@ import path from 'path';
54
55
  return null;
55
56
  }
56
57
  }
58
+ /** Read a dotenv-parsed value without populating process.env. */ export function getParsedEnvVarSync(projectPath, key) {
59
+ try {
60
+ const contents = fsSync.readFileSync(path.join(projectPath, '.env'), 'utf-8');
61
+ return parse(contents)[key] ?? null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
57
66
  /**
58
67
  * Add or update an environment variable in .env file
59
68
  *
@@ -115,6 +124,44 @@ import path from 'path';
115
124
  throw new Error(`Failed to update .env file: ${error instanceof Error ? error.message : 'Unknown error'}`);
116
125
  }
117
126
  }
127
+ /**
128
+ * Comment out an environment variable in .env file by prepending `# ` to any
129
+ * assignment line for the given key. Preserves the value so the developer can
130
+ * uncomment it later (or move it to another env file). No-op if the key is
131
+ * absent or every occurrence is already commented.
132
+ *
133
+ * @param projectPath - Path to project directory
134
+ * @param key - Environment variable name to disable
135
+ * @param annotation - Optional trailing comment appended to each disabled
136
+ * line, so the developer knows why it was disabled
137
+ * @returns true if at least one line was commented out, false otherwise
138
+ */ export async function commentOutEnvVar(projectPath, key, annotation) {
139
+ const envPath = path.join(projectPath, '.env');
140
+ try {
141
+ const contents = await fs.readFile(envPath, 'utf-8');
142
+ const lines = contents.split(/\r?\n/);
143
+ let changed = false;
144
+ const updated = lines.map((line)=>{
145
+ if (!line.includes('=') || line.trim().startsWith('#')) {
146
+ return line;
147
+ }
148
+ const equalsIndex = line.indexOf('=');
149
+ const lineKey = line.substring(0, equalsIndex).trim();
150
+ if (lineKey !== key) {
151
+ return line;
152
+ }
153
+ changed = true;
154
+ const suffix = annotation ? ` # ${annotation}` : '';
155
+ return `# ${line}${suffix}`;
156
+ });
157
+ if (changed) {
158
+ await fs.writeFile(envPath, updated.join('\n'), 'utf-8');
159
+ }
160
+ return changed;
161
+ } catch {
162
+ return false;
163
+ }
164
+ }
118
165
  /**
119
166
  * Remove an environment variable from .env file
120
167
  *
@@ -88,7 +88,10 @@ import * as log from './log.js';
88
88
  }
89
89
  }
90
90
  }
91
- // Check for secret property
91
+ // Check for secret property. The platform owns PAYLOAD_SECRET, so the
92
+ // scaffolded `secret: process.env.PAYLOAD_SECRET` line is stripped —
93
+ // `buildFigmaConfig` injects the value at runtime from the env var (in
94
+ // Lambda) or the TokenStore cache (local dev).
92
95
  const secretProperty = configArg.getProperty('secret');
93
96
  if (secretProperty) {
94
97
  result.secretProperty = true;
@@ -252,7 +255,7 @@ import * as log from './log.js';
252
255
  modified = true;
253
256
  }
254
257
  }
255
- // 2. Remove secret property
258
+ // 2. Remove secret property (platform-managed)
256
259
  if (detection.secretProperty) {
257
260
  const secretProperty = configArg.getProperty('secret');
258
261
  if (secretProperty) {
@@ -0,0 +1,28 @@
1
+ import type { AuthCredential } from '../auth/credentials.js';
2
+ import type { TokenStore } from '../auth/token-store.js';
3
+ import type { ProjectStoreScope } from '../auth/types.js';
4
+ export declare const PAYLOAD_SECRET_ENV_VAR = "PAYLOAD_SECRET";
5
+ interface EnsurePayloadSecretArgs {
6
+ credential: AuthCredential;
7
+ projectInfo: ProjectStoreScope;
8
+ /** Fetch the current platform value even when cached, preserving the cache on failure. */
9
+ refresh?: boolean;
10
+ tenantInstanceId: string;
11
+ tokenStore: TokenStore;
12
+ }
13
+ /**
14
+ * Resolve the tenant's PAYLOAD_SECRET and cache it in the encrypted
15
+ * TokenStore. The secret is intentionally NOT written to `.env`: keeping it
16
+ * only in the machine-scoped, AES-256-GCM-encrypted store avoids the
17
+ * plaintext-on-disk / accidental-exfiltration risks of a project-local file.
18
+ * `buildFigmaConfig` reads it back from the TokenStore at dev/build time.
19
+ *
20
+ * The Figma platform owns PAYLOAD_SECRET rotation; this helper never
21
+ * generates or mutates the value — it only fetches whatever the Control
22
+ * Plane currently returns and caches it.
23
+ *
24
+ * Non-fatal on failure: callers should catch and log rather than abort init,
25
+ * so the sinatra endpoint rollout can lag the CLI.
26
+ */
27
+ export declare function ensurePayloadSecret({ credential, projectInfo, refresh, tenantInstanceId, tokenStore, }: EnsurePayloadSecretArgs): Promise<string>;
28
+ export {};
@@ -0,0 +1,34 @@
1
+ import { getEnvironmentVariableByName } from '../api/control-plane.js';
2
+ import * as log from './log.js';
3
+ export const PAYLOAD_SECRET_ENV_VAR = 'PAYLOAD_SECRET';
4
+ /**
5
+ * Resolve the tenant's PAYLOAD_SECRET and cache it in the encrypted
6
+ * TokenStore. The secret is intentionally NOT written to `.env`: keeping it
7
+ * only in the machine-scoped, AES-256-GCM-encrypted store avoids the
8
+ * plaintext-on-disk / accidental-exfiltration risks of a project-local file.
9
+ * `buildFigmaConfig` reads it back from the TokenStore at dev/build time.
10
+ *
11
+ * The Figma platform owns PAYLOAD_SECRET rotation; this helper never
12
+ * generates or mutates the value — it only fetches whatever the Control
13
+ * Plane currently returns and caches it.
14
+ *
15
+ * Non-fatal on failure: callers should catch and log rather than abort init,
16
+ * so the sinatra endpoint rollout can lag the CLI.
17
+ */ export async function ensurePayloadSecret({ credential, projectInfo, refresh = false, tenantInstanceId, tokenStore }) {
18
+ const cached = tokenStore.getPayloadSecret({
19
+ projectInfo
20
+ });
21
+ if (cached && !refresh) {
22
+ return cached;
23
+ }
24
+ const secret = await getEnvironmentVariableByName(credential, tenantInstanceId, PAYLOAD_SECRET_ENV_VAR);
25
+ if (!secret) {
26
+ throw new Error('Control Plane returned an empty PAYLOAD_SECRET');
27
+ }
28
+ tokenStore.setPayloadSecret({
29
+ projectInfo,
30
+ secret
31
+ });
32
+ log.debug(`Cached PAYLOAD_SECRET for ${projectInfo.projectId}:${projectInfo.environmentName}`);
33
+ return secret;
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/figma",
3
- "version": "0.1.0-alpha.10",
3
+ "version": "0.1.0-alpha.11",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "type": "module",
6
6
  "exports": {
@@ -45,6 +45,7 @@
45
45
  "arg": "^5.0.2",
46
46
  "conf": "^13.1.0",
47
47
  "cross-spawn": "7.0.6",
48
+ "dotenv": "^16.4.5",
48
49
  "env-paths": "^3.0.0",
49
50
  "figures": "^6.1.0",
50
51
  "jose": "6.0.12",
@@ -63,33 +64,34 @@
63
64
  "devDependencies": {
64
65
  "@payloadcms/eslint-config": "3.28.0",
65
66
  "@payloadcms/eslint-plugin": "3.28.0",
66
- "@payloadcms/next": "4.0.0-canary.28",
67
- "@payloadcms/plugin-cloud-storage": "4.0.0-canary.28",
68
- "@payloadcms/richtext-lexical": "4.0.0-canary.28",
69
- "@payloadcms/translations": "4.0.0-canary.28",
70
- "@payloadcms/ui": "4.0.0-canary.28",
67
+ "@payloadcms/next": "4.0.0-canary.37",
68
+ "@payloadcms/plugin-cloud-storage": "4.0.0-canary.37",
69
+ "@payloadcms/richtext-lexical": "4.0.0-canary.37",
70
+ "@payloadcms/translations": "4.0.0-canary.37",
71
+ "@payloadcms/ui": "4.0.0-canary.37",
71
72
  "@swc/cli": "0.7.7",
72
73
  "@types/archiver": "7.0.0",
73
74
  "@types/cross-spawn": "6.0.6",
74
75
  "@types/jsonwebtoken": "^9.0.10",
75
76
  "@types/node": "^24.0.0",
77
+ "@types/react": "^19",
76
78
  "@types/uuid": "^8.3.4",
77
79
  "copyfiles": "^2.4.1",
78
80
  "eslint": "9.22.0",
79
81
  "next": "^16.3.3",
80
82
  "openapi-typescript": "^7.13.0",
81
- "payload": "4.0.0-canary.28",
83
+ "payload": "4.0.0-canary.37",
82
84
  "rimraf": "^6.1.3",
83
85
  "tsx": "4.20.6",
84
86
  "typescript": "5.7.3",
85
87
  "vitest": "4.0.15"
86
88
  },
87
89
  "peerDependencies": {
88
- "@payloadcms/plugin-cloud-storage": ">=4.0.0-canary.28 <4.0.0-internal",
89
- "@payloadcms/richtext-lexical": ">=4.0.0-canary.28 <4.0.0-internal",
90
- "@payloadcms/translations": ">=4.0.0-canary.28 <4.0.0-internal",
91
- "@payloadcms/ui": ">=4.0.0-canary.28 <4.0.0-internal",
92
- "payload": ">=4.0.0-canary.28 <4.0.0-internal",
90
+ "@payloadcms/plugin-cloud-storage": ">=4.0.0-canary.37 <4.0.0-internal",
91
+ "@payloadcms/richtext-lexical": ">=4.0.0-canary.37 <4.0.0-internal",
92
+ "@payloadcms/translations": ">=4.0.0-canary.37 <4.0.0-internal",
93
+ "@payloadcms/ui": ">=4.0.0-canary.37 <4.0.0-internal",
94
+ "payload": ">=4.0.0-canary.37 <4.0.0-internal",
93
95
  "react": "^19.0.1 || ^19.1.2 || ^19.2.1"
94
96
  },
95
97
  "peerDependenciesMeta": {