@payloadcms/figma 0.1.0-alpha.11 → 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 (43) hide show
  1. package/dist/api/control-plane.d.ts +2 -0
  2. package/dist/api/control-plane.js +1 -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/types.d.ts +5 -3
  9. package/dist/commands/bootstrap.js +3 -0
  10. package/dist/commands/upload-schema.js +3 -4
  11. package/dist/config/oauth.js +6 -1
  12. package/dist/constants.d.ts +0 -2
  13. package/dist/constants.js +0 -3
  14. package/dist/plugin/build-config.js +76 -16
  15. package/dist/storage-content-api/api-types.d.ts +2 -2
  16. package/dist/storage-content-api/buildClientUploadFetchBackHeaders.d.ts +1 -1
  17. package/dist/storage-content-api/client-uploads/generate.d.ts +7 -3
  18. package/dist/storage-content-api/client-uploads/generate.js +20 -20
  19. package/dist/storage-content-api/copyFile.d.ts +16 -0
  20. package/dist/storage-content-api/copyFile.js +90 -0
  21. package/dist/storage-content-api/deleteFile.d.ts +8 -0
  22. package/dist/storage-content-api/deleteFile.js +18 -0
  23. package/dist/storage-content-api/handleUpload.d.ts +1 -2
  24. package/dist/storage-content-api/handleUpload.js +13 -157
  25. package/dist/storage-content-api/index.js +16 -8
  26. package/dist/storage-content-api/staticHandler.d.ts +2 -1
  27. package/dist/storage-content-api/staticHandler.js +14 -27
  28. package/dist/storage-content-api/uploadFileData.d.ts +10 -0
  29. package/dist/storage-content-api/uploadFileData.js +145 -0
  30. package/dist/utils/cache-bootstrap.js +1 -0
  31. package/dist/utils/load-payload-config.js +1 -6
  32. package/dist/utils/payload-config-ast.d.ts +5 -0
  33. package/dist/utils/payload-config-ast.js +68 -2
  34. package/dist/utils/payload-config-modifier.js +3 -0
  35. package/package.json +13 -13
  36. package/dist/storage-content-api/handleDelete.d.ts +0 -7
  37. package/dist/storage-content-api/handleDelete.js +0 -15
  38. package/dist/storage-content-api/utilities/getSafeFilename.d.ts +0 -11
  39. package/dist/storage-content-api/utilities/getSafeFilename.js +0 -59
  40. package/dist/storage-content-api/utilities/index.d.ts +0 -2
  41. package/dist/storage-content-api/utilities/index.js +0 -2
  42. package/dist/storage-content-api/utilities/parseUploadReference.d.ts +0 -17
  43. 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;
@@ -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
  })),
@@ -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
+ }
@@ -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
  }
@@ -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
  }
@@ -167,6 +167,64 @@ 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
  }
@@ -273,21 +331,22 @@ export async function buildFigmaConfig(config) {
273
331
  let environmentId = config.figma.environmentId ?? process.env.FIGMA_EID;
274
332
  contentSystemId ??= process.env.FIGMA_CONTENT_API_CONTENT_SYSTEM_ID;
275
333
  let bootstrapData = null;
334
+ let bootstrapFetched = false;
276
335
  let bootstrapReason = null;
277
336
  // Local dev: resolve from project ID + bootstrap cache
278
- // Use getEnvVarSync fallback because Next.js evaluates config before dotenv populates process.env
279
337
  if (!contentSystemId) {
280
- const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
281
- const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
282
- if (!projectId || !environmentName) {
338
+ const scope = readProjectScope();
339
+ if (!scope) {
283
340
  bootstrapReason = {
284
341
  kind: 'no-config'
285
342
  };
286
343
  } else {
344
+ const { environmentName, projectId } = scope;
287
345
  const store = getTokenStore();
288
346
  bootstrapData = store.getBootstrapData(projectId, environmentName);
289
347
  // Runtime fallback: fetch from API if not cached (e.g. environment switch without re-init)
290
348
  if (!bootstrapData) {
349
+ bootstrapFetched = true;
291
350
  const resolution = await resolveAndCacheBootstrap(store, projectId, environmentName);
292
351
  if (resolution.ok) {
293
352
  bootstrapData = resolution.data;
@@ -302,12 +361,8 @@ export async function buildFigmaConfig(config) {
302
361
  }
303
362
  }
304
363
  if (!environmentId) {
305
- const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
306
- const environmentName = process.env.FIGMA_ENVIRONMENT_NAME ?? getEnvVarSync(process.cwd(), 'FIGMA_ENVIRONMENT_NAME');
307
- if (projectId && environmentName) {
308
- bootstrapData ??= getTokenStore().getBootstrapData(projectId, environmentName);
309
- environmentId = bootstrapData?.tenantInstanceId;
310
- }
364
+ bootstrapData ??= readCachedBootstrapData();
365
+ environmentId = bootstrapData?.tenantInstanceId;
311
366
  }
312
367
  if (!environmentId) {
313
368
  throw new Error('Environment ID could not be resolved. Set FIGMA_EID or initialize the project.');
@@ -318,7 +373,13 @@ export async function buildFigmaConfig(config) {
318
373
  });
319
374
  throw new Error('Content System ID could not be resolved. ' + 'Run `npx @payloadcms/figma init` to set up your project.');
320
375
  }
321
- 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
+ }) : '';
322
383
  const isProduction = process.env.NODE_ENV === 'production';
323
384
  // The deployed Lambda runs all queued jobs; locally there is no runner, so the db adapter logs
324
385
  // a heads-up whenever a job is queued. Deployed environments set DISABLE_LOCAL_JOB_QUEUE_NOTIFICATIONS=true
@@ -330,7 +391,6 @@ export async function buildFigmaConfig(config) {
330
391
  }
331
392
  // Determine database adapter based on environment
332
393
  let db;
333
- const usesContentSystem = config.figma.useContentSystem !== false;
334
394
  if (!usesContentSystem) {
335
395
  db = config.db;
336
396
  } else if (process.env.FIGMA_CONTENT_API_ACCESS_KEY) {
@@ -368,11 +428,11 @@ export async function buildFigmaConfig(config) {
368
428
  }
369
429
  const userJobsAccessRun = config.jobs?.access?.run;
370
430
  const adminCollectionSlug = getAdminCollectionSlug(config);
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.
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.
374
434
  let resolvedSecret;
375
- if (process.env.AWS_EXECUTION_ENV) {
435
+ if (process.env.AWS_EXECUTION_ENV || process.env.FIGMA_CONTENT_API_ACCESS_KEY) {
376
436
  resolvedSecret = process.env.PAYLOAD_SECRET;
377
437
  } else {
378
438
  const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID');
@@ -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': {
@@ -59,7 +59,7 @@ export type UploadPaths = {
59
59
  };
60
60
  };
61
61
  };
62
- };
62
+ } & UploadErrorResponses;
63
63
  };
64
64
  };
65
65
  '/api/v0/uploads/multipart/abort': {
@@ -6,7 +6,7 @@
6
6
  * is present; normal file requests use buildMediaResponseHeaders.
7
7
  */
8
8
  export declare function buildClientUploadFetchBackHeaders({ fallbackContentType, filename, upstreamHeaders, }: {
9
- fallbackContentType: string | undefined;
9
+ fallbackContentType?: string;
10
10
  filename: string;
11
11
  upstreamHeaders: Headers;
12
12
  }): Headers;
@@ -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 {};