@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
@@ -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';
@@ -167,9 +167,110 @@ function missingOAuthCredential(name) {
167
167
  ok: true
168
168
  };
169
169
  }
170
+ /**
171
+ * Project + environment named in process.env or .env. Uses getEnvVarSync because Next.js
172
+ * evaluates config before dotenv populates process.env.
173
+ */ function readProjectScope() {
174
+ const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
175
+ const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
176
+ if (!projectId || !environmentName) {
177
+ return null;
178
+ }
179
+ return {
180
+ environmentName,
181
+ projectId
182
+ };
183
+ }
184
+ function readCachedBootstrapData() {
185
+ const scope = readProjectScope();
186
+ return scope ? getTokenStore().getBootstrapData(scope.projectId, scope.environmentName) : null;
187
+ }
188
+ /**
189
+ * Resolve the Content API base URL: FIGMA_CONTENT_API_URL (injected in deployed environments),
190
+ * then the environment's regional URL from the bootstrap cache. A cached entry without a URL
191
+ * (written before bootstrap returned one) is refreshed from the API, unless this build already
192
+ * fetched bootstrap. Throws when no URL can be resolved.
193
+ */ async function requireContentApiUrl(args) {
194
+ if (process.env.FIGMA_CONTENT_API_URL) {
195
+ return process.env.FIGMA_CONTENT_API_URL;
196
+ }
197
+ const cached = args.bootstrapData ?? readCachedBootstrapData();
198
+ if (cached?.contentApiUrl) {
199
+ return cached.contentApiUrl;
200
+ }
201
+ const scope = readProjectScope();
202
+ if (!scope) {
203
+ throw new Error('Could not resolve the Content API URL.');
204
+ }
205
+ const message = `Could not resolve the Content API URL for environment "${scope.environmentName}" of project ${scope.projectId}.`;
206
+ if (args.bootstrapFetched) {
207
+ throw new Error(message);
208
+ }
209
+ const resolution = await resolveAndCacheBootstrap(getTokenStore(), scope.projectId, scope.environmentName);
210
+ if (!resolution.ok) {
211
+ throw new Error(`${message} ${describeBootstrapFailure(resolution.reason)}`);
212
+ }
213
+ if (!resolution.data.contentApiUrl) {
214
+ throw new Error(message);
215
+ }
216
+ return resolution.data.contentApiUrl;
217
+ }
218
+ function describeBootstrapFailure(reason) {
219
+ switch(reason.kind){
220
+ case 'environment-not-found':
221
+ return 'Fetching bootstrap data failed: environment not found.';
222
+ case 'network':
223
+ return `Fetching bootstrap data failed: ${reason.message}`;
224
+ case 'unauthenticated':
225
+ return 'Fetching bootstrap data failed: not logged in.';
226
+ }
227
+ }
170
228
  function messageOf(error) {
171
229
  return error instanceof Error ? error.message : 'Unknown error';
172
230
  }
231
+ /**
232
+ * Local-dev fallback: if the tenant config didn't supply a secret (usually
233
+ * because process.env.PAYLOAD_SECRET is unset), try the TokenStore cache,
234
+ * then fetch from the Control Plane. Skipped in Lambda — the platform
235
+ * injects PAYLOAD_SECRET as an env var there, and TokenStore throws in AWS.
236
+ * Returns undefined if we can't resolve one; the caller lets payload.init()
237
+ * throw its own error.
238
+ */ async function resolvePayloadSecretForRuntime(store, projectId, environmentName, tenantInstanceId) {
239
+ const cached = store.getPayloadSecret({
240
+ projectInfo: {
241
+ environmentName,
242
+ projectId
243
+ }
244
+ });
245
+ if (cached) {
246
+ return cached;
247
+ }
248
+ let credential;
249
+ try {
250
+ credential = await getValidCredential(store);
251
+ } catch (error) {
252
+ log.debug(`PAYLOAD_SECRET fetch skipped: ${messageOf(error)}`);
253
+ return undefined;
254
+ }
255
+ if (!credential) {
256
+ log.debug('PAYLOAD_SECRET fetch skipped: no cached CLI credential');
257
+ return undefined;
258
+ }
259
+ try {
260
+ const secret = await getEnvironmentVariableByName(credential, tenantInstanceId, 'PAYLOAD_SECRET');
261
+ store.setPayloadSecret({
262
+ projectInfo: {
263
+ environmentName,
264
+ projectId
265
+ },
266
+ secret
267
+ });
268
+ return secret;
269
+ } catch (error) {
270
+ log.debug(`PAYLOAD_SECRET fetch failed: ${messageOf(error)}`);
271
+ return undefined;
272
+ }
273
+ }
173
274
  /**
174
275
  * Creates storage configuration for upload collections
175
276
  */ function createStorageConfig(url, contentSystemId, uploadInstructionsAccess) {
@@ -230,21 +331,22 @@ export async function buildFigmaConfig(config) {
230
331
  let environmentId = config.figma.environmentId ?? process.env.FIGMA_EID;
231
332
  contentSystemId ??= process.env.FIGMA_CONTENT_API_CONTENT_SYSTEM_ID;
232
333
  let bootstrapData = null;
334
+ let bootstrapFetched = false;
233
335
  let bootstrapReason = null;
234
336
  // Local dev: resolve from project ID + bootstrap cache
235
- // Use getEnvVarSync fallback because Next.js evaluates config before dotenv populates process.env
236
337
  if (!contentSystemId) {
237
- const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
238
- const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
239
- if (!projectId || !environmentName) {
338
+ const scope = readProjectScope();
339
+ if (!scope) {
240
340
  bootstrapReason = {
241
341
  kind: 'no-config'
242
342
  };
243
343
  } else {
344
+ const { environmentName, projectId } = scope;
244
345
  const store = getTokenStore();
245
346
  bootstrapData = store.getBootstrapData(projectId, environmentName);
246
347
  // Runtime fallback: fetch from API if not cached (e.g. environment switch without re-init)
247
348
  if (!bootstrapData) {
349
+ bootstrapFetched = true;
248
350
  const resolution = await resolveAndCacheBootstrap(store, projectId, environmentName);
249
351
  if (resolution.ok) {
250
352
  bootstrapData = resolution.data;
@@ -259,12 +361,8 @@ export async function buildFigmaConfig(config) {
259
361
  }
260
362
  }
261
363
  if (!environmentId) {
262
- const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
263
- const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
264
- if (projectId && environmentName) {
265
- bootstrapData ??= getTokenStore().getBootstrapData(projectId, environmentName);
266
- environmentId = bootstrapData?.tenantInstanceId;
267
- }
364
+ bootstrapData ??= readCachedBootstrapData();
365
+ environmentId = bootstrapData?.tenantInstanceId;
268
366
  }
269
367
  if (!environmentId) {
270
368
  throw new Error('Environment ID could not be resolved. Set FIGMA_EID or initialize the project.');
@@ -275,7 +373,13 @@ export async function buildFigmaConfig(config) {
275
373
  });
276
374
  throw new Error('Content System ID could not be resolved. ' + 'Run `npx @payloadcms/figma init` to set up your project.');
277
375
  }
278
- const url = process.env.FIGMA_CONTENT_API_URL || envConfig.contentApiUrl;
376
+ // Only the content-system db adapter and cloud storage call the Content API, so a project on a
377
+ // custom db with storage disabled needs no URL; `url` stays '' and is unused in that case.
378
+ const usesContentSystem = config.figma.useContentSystem !== false;
379
+ const url = usesContentSystem || config.figma.storage !== false ? await requireContentApiUrl({
380
+ bootstrapData,
381
+ bootstrapFetched
382
+ }) : '';
279
383
  const isProduction = process.env.NODE_ENV === 'production';
280
384
  // The deployed Lambda runs all queued jobs; locally there is no runner, so the db adapter logs
281
385
  // a heads-up whenever a job is queued. Deployed environments set DISABLE_LOCAL_JOB_QUEUE_NOTIFICATIONS=true
@@ -287,7 +391,6 @@ export async function buildFigmaConfig(config) {
287
391
  }
288
392
  // Determine database adapter based on environment
289
393
  let db;
290
- const usesContentSystem = config.figma.useContentSystem !== false;
291
394
  if (!usesContentSystem) {
292
395
  db = config.db;
293
396
  } else if (process.env.FIGMA_CONTENT_API_ACCESS_KEY) {
@@ -325,7 +428,30 @@ export async function buildFigmaConfig(config) {
325
428
  }
326
429
  const userJobsAccessRun = config.jobs?.access?.run;
327
430
  const adminCollectionSlug = getAdminCollectionSlug(config);
328
- // Build complete config with Figma platform defaults
431
+ // Hosted runtimes inject the Content API key and PAYLOAD_SECRET together, so
432
+ // the process env is authoritative. Ordinary local dev still checks the
433
+ // TokenStore first so a leftover .env value cannot shadow the platform secret.
434
+ let resolvedSecret;
435
+ if (process.env.AWS_EXECUTION_ENV || process.env.FIGMA_CONTENT_API_ACCESS_KEY) {
436
+ resolvedSecret = process.env.PAYLOAD_SECRET;
437
+ } else {
438
+ const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
439
+ const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
440
+ if (projectId && environmentName && environmentId) {
441
+ resolvedSecret = await resolvePayloadSecretForRuntime(getTokenStore(), projectId, environmentName, environmentId);
442
+ }
443
+ if (!resolvedSecret) {
444
+ // Config may be evaluated before the framework loads dotenv. Parse the
445
+ // file without mutating process.env, preserving quotes/comments correctly.
446
+ resolvedSecret = process.env.PAYLOAD_SECRET || getParsedEnvVarSync(process.cwd(), 'PAYLOAD_SECRET') || undefined;
447
+ if (resolvedSecret) {
448
+ 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.');
449
+ }
450
+ }
451
+ }
452
+ // Build complete config with Figma platform defaults.
453
+ // `secret` may be undefined here; payload.init() enforces its presence at
454
+ // runtime, so we relax the intermediate type instead of forging a default.
329
455
  const configWithFigmaDefaults = {
330
456
  ...config,
331
457
  admin: {
@@ -367,6 +493,7 @@ export async function buildFigmaConfig(config) {
367
493
  ...config.i18n,
368
494
  translations: deepMergeSimple(figmaTranslations, config.i18n?.translations ?? {})
369
495
  },
496
+ secret: resolvedSecret,
370
497
  // Gate /api/payload-jobs/run and /api/payload-jobs/handle-schedules. Honor the
371
498
  // sites-worker trust marker so Figma infra job runs never break, defer to the
372
499
  // tenant's jobs.access.run if they set one, otherwise require an authenticated
@@ -386,14 +513,28 @@ export async function buildFigmaConfig(config) {
386
513
  // explicit view, and other unrecognized values.
387
514
  return Boolean(args.req.user) && passesMakeViewerWriteGate(args.req.user);
388
515
  }
389
- }
516
+ },
517
+ // Remove Payload's default read/write denials so the jobs collection uses
518
+ // the standard access defaults and baseAccess Make-permission write gate.
519
+ // Preserve tenant-supplied overrides; jobs.access.run separately controls
520
+ // the job execution endpoints.
521
+ jobsCollectionOverrides: config.jobs?.jobsCollectionOverrides ?? (({ defaultJobsCollection })=>{
522
+ const { access: _access, ...rest } = defaultJobsCollection;
523
+ return rest;
524
+ })
390
525
  },
391
526
  ...isProduction && !config.logger ? {
392
527
  logger: {
393
528
  options: {}
394
529
  }
395
530
  } : {},
396
- secret: 'MY_SECRET',
531
+ // The platform owns rotation of PAYLOAD_SECRET; this compat entry lets
532
+ // data encrypted under the old shared hosted secret keep decrypting.
533
+ // Appended last so any tenant-supplied previousSecrets are honored first.
534
+ previousSecrets: [
535
+ ...config.previousSecrets ?? [],
536
+ Buffer.from('TVlfU0VDUkVU', 'base64').toString('utf8')
537
+ ],
397
538
  // Add oauth to plugins if not already present
398
539
  plugins: [
399
540
  ...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;
@@ -34,7 +34,7 @@ export type UploadPaths = {
34
34
  };
35
35
  };
36
36
  };
37
- };
37
+ } & UploadErrorResponses;
38
38
  };
39
39
  };
40
40
  '/api/v0/uploads/download/sign': {
@@ -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
  };
@@ -56,7 +59,7 @@ export type UploadPaths = {
56
59
  };
57
60
  };
58
61
  };
59
- };
62
+ } & UploadErrorResponses;
60
63
  };
61
64
  };
62
65
  '/api/v0/uploads/multipart/abort': {
@@ -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;
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
+ }
@@ -3,12 +3,16 @@ import type { StorageClient } from '../client.js';
3
3
  type Args = {
4
4
  access?: UploadInstructionsAccess;
5
5
  client: StorageClient;
6
+ collectionPrefix?: string;
6
7
  };
7
8
  /**
8
9
  * v4 client-upload entry point. Payload core calls this from
9
10
  * `POST /api/upload-instructions`; we sign a Content API upload URL and hand the
10
- * browser an `http` PUT instruction plus an `uploadReference` that
11
- * `handleUpload`/`staticHandler` use to recognize the already-uploaded file.
11
+ * browser an `http` PUT instruction plus a signed upload receipt.
12
+ *
13
+ * Each upload gets its own `_objectKey`, so it never overwrites another object.
14
+ * Payload verifies the receipt before it reads the uploaded file back through
15
+ * `staticHandler`, and it does not upload the original again in `handleUpload`.
12
16
  */
13
- export declare const getGenerateUploadInstructions: ({ access, client, }: Args) => GenerateUploadInstructions;
17
+ export declare const getGenerateUploadInstructions: ({ access, client, collectionPrefix, }: Args) => GenerateUploadInstructions;
14
18
  export {};
@@ -1,14 +1,17 @@
1
- import path from 'path';
1
+ import { resolveSignedURLKey } from '@payloadcms/plugin-cloud-storage/utilities';
2
2
  import { APIError, Forbidden } from 'payload';
3
+ import { assertClientUploadAllowed } from 'payload/internal';
3
4
  import { passesMakeViewerWriteGate } from '../../plugin/make-permission-access/make-permission-access.js';
4
- import { getSafeFilename } from '../utilities/index.js';
5
5
  const defaultAccess = ({ req })=>Boolean(req.user) && passesMakeViewerWriteGate(req.user);
6
6
  /**
7
7
  * v4 client-upload entry point. Payload core calls this from
8
8
  * `POST /api/upload-instructions`; we sign a Content API upload URL and hand the
9
- * browser an `http` PUT instruction plus an `uploadReference` that
10
- * `handleUpload`/`staticHandler` use to recognize the already-uploaded file.
11
- */ export const getGenerateUploadInstructions = ({ access = defaultAccess, client })=>{
9
+ * browser an `http` PUT instruction plus a signed upload receipt.
10
+ *
11
+ * Each upload gets its own `_objectKey`, so it never overwrites another object.
12
+ * Payload verifies the receipt before it reads the uploaded file back through
13
+ * `staticHandler`, and it does not upload the original again in `handleUpload`.
14
+ */ export const getGenerateUploadInstructions = ({ access = defaultAccess, client, collectionPrefix = '' })=>{
12
15
  const generate = async ({ collectionSlug, docPrefix, filename, filesize, mimeType, overrideAccess, req })=>{
13
16
  if (!overrideAccess && !await access({
14
17
  collectionSlug,
@@ -16,21 +19,24 @@ const defaultAccess = ({ req })=>Boolean(req.user) && passesMakeViewerWriteGate(
16
19
  })) {
17
20
  throw new Forbidden();
18
21
  }
19
- const safeFilename = await getSafeFilename({
22
+ assertClientUploadAllowed({
23
+ collection: req.payload.collections[collectionSlug]?.config,
24
+ filename,
25
+ mimeType
26
+ });
27
+ const { sanitizedFilename, storageFilePath, uploadReference } = await resolveSignedURLKey({
28
+ collectionPrefix,
20
29
  collectionSlug,
21
- desiredFilename: filename,
30
+ docPrefix,
31
+ filename,
22
32
  req
23
33
  });
24
- // Key by `<prefix>/<filename>` to match the read path (staticHandler/generateURL
25
- // via getFilePrefix) and handleUpload. The Figma plugin sets no prefix, so
26
- // docPrefix is blank today and this is just the filename.
27
- const fileKey = path.posix.join(docPrefix ?? '', safeFilename);
28
34
  const { data, error, response } = await client.POST('/api/v0/uploads/sign', {
29
35
  body: {
30
36
  collectionId: collectionSlug,
31
37
  contentType: mimeType,
32
38
  expiresIn: 3600,
33
- filename: fileKey
39
+ filename: storageFilePath
34
40
  }
35
41
  });
36
42
  if (error) {
@@ -44,16 +50,10 @@ const defaultAccess = ({ req })=>Boolean(req.user) && passesMakeViewerWriteGate(
44
50
  return {
45
51
  type: 'http',
46
52
  file: {
47
- collectionSlug,
48
- filename: safeFilename,
53
+ filename: sanitizedFilename,
49
54
  mimeType,
50
55
  size: filesize,
51
- uploadReference: {
52
- clientUploaded: true,
53
- filename: safeFilename,
54
- mimeType,
55
- prefix: docPrefix ?? ''
56
- }
56
+ uploadReference
57
57
  },
58
58
  // The presigned URL is signed with `contentType: mimeType`, so the browser
59
59
  // PUT must carry a matching Content-Type header or S3 rejects the signature.
@@ -0,0 +1,16 @@
1
+ import type { CopyFile } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { StorageClient } from './client.js';
3
+ type Args = {
4
+ client: StorageClient;
5
+ };
6
+ /**
7
+ * Copies `from` to `to` and keeps `from`, so older versions can still read it.
8
+ *
9
+ * The Content API has no copy endpoint, so the bytes are downloaded and uploaded again with
10
+ * the source Content-Type. The Content API stores no other object metadata.
11
+ *
12
+ * The destination check is not atomic. Payload puts a new `_objectKey` in `to`, so two
13
+ * copies to the same key at the same time are not expected.
14
+ */
15
+ export declare const getCopyFile: ({ client }: Args) => CopyFile;
16
+ export {};
@@ -0,0 +1,90 @@
1
+ import { APIError } from 'payload';
2
+ import { uploadFileData } from './uploadFileData.js';
3
+ const PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS = 300;
4
+ /**
5
+ * Copies `from` to `to` and keeps `from`, so older versions can still read it.
6
+ *
7
+ * The Content API has no copy endpoint, so the bytes are downloaded and uploaded again with
8
+ * the source Content-Type. The Content API stores no other object metadata.
9
+ *
10
+ * The destination check is not atomic. Payload puts a new `_objectKey` in `to`, so two
11
+ * copies to the same key at the same time are not expected.
12
+ */ export const getCopyFile = ({ client })=>{
13
+ return async ({ collection, from, mimeType, req, to })=>{
14
+ if (from === to) {
15
+ throw new Error('Storage copy requires different source and destination keys');
16
+ }
17
+ const collectionId = collection.slug;
18
+ // The Content API role can list the bucket, so a missing object returns 404, not 403.
19
+ const destination = await fetchObject({
20
+ client,
21
+ collectionId,
22
+ headers: {
23
+ Range: 'bytes=0-0'
24
+ },
25
+ key: to,
26
+ signal: req.signal
27
+ });
28
+ await cancelResponseBody(destination);
29
+ if (destination.status !== 404) {
30
+ if (destination.ok || destination.status === 416) {
31
+ throw new APIError(`Storage destination already exists: ${to}`, 409);
32
+ }
33
+ throw new Error(`Failed to check storage destination: ${destination.status}`);
34
+ }
35
+ const source = await fetchObject({
36
+ client,
37
+ collectionId,
38
+ key: from,
39
+ signal: req.signal
40
+ });
41
+ if (!source.ok) {
42
+ await cancelResponseBody(source);
43
+ throw new Error(`Failed to read storage source: ${source.status}`);
44
+ }
45
+ const fileData = Buffer.from(await source.arrayBuffer());
46
+ await uploadFileData({
47
+ client,
48
+ collectionId,
49
+ fileData,
50
+ fileKey: to,
51
+ mimeType: source.headers.get('Content-Type') || mimeType || 'application/octet-stream'
52
+ });
53
+ };
54
+ };
55
+ async function fetchObject({ client, collectionId, headers, key, signal }) {
56
+ const { data, error, response } = await client.POST('/api/v0/uploads/download/sign', {
57
+ body: {
58
+ collectionId,
59
+ expiresIn: PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS,
60
+ filename: key,
61
+ responseHeaders: {
62
+ cacheControl: 'private, no-store'
63
+ }
64
+ }
65
+ });
66
+ if (error) {
67
+ throw new APIError(`Failed to get presigned download URL: ${error.message}`, response.status, {
68
+ code: error.code
69
+ });
70
+ }
71
+ if (!data) {
72
+ throw new Error('No response while getting presigned download URL');
73
+ }
74
+ try {
75
+ return await fetch(data.url, {
76
+ headers,
77
+ signal
78
+ });
79
+ } catch {
80
+ // Fetch errors can contain the signed URL; throw only a fixed message to avoid exposing it.
81
+ throw new Error('Failed to fetch file from storage');
82
+ }
83
+ }
84
+ async function cancelResponseBody(response) {
85
+ try {
86
+ await response.body?.cancel();
87
+ } catch {
88
+ // The body is not read; cancellation is best-effort cleanup.
89
+ }
90
+ }