@payloadcms/figma 1.0.0-beta.1 → 1.0.0-internal.d040868

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 (37) hide show
  1. package/dist/adapters/build-lambda-zip.d.ts +2 -1
  2. package/dist/adapters/build-lambda-zip.js +4 -1
  3. package/dist/adapters/deploy-output/assertDeployableServerActionsKey.d.ts +14 -0
  4. package/dist/adapters/deploy-output/assertDeployableServerActionsKey.js +33 -0
  5. package/dist/commands/upload-schema.js +23 -9
  6. package/dist/db-content-api/index.js +37 -0
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.js +1 -0
  9. package/dist/oauth/hooks/me.d.ts +4 -3
  10. package/dist/oauth/hooks/me.js +6 -52
  11. package/dist/oauth/hooks/refresh.js +9 -1
  12. package/dist/oauth/index.js +1 -1
  13. package/dist/oauth/strategy/index.d.ts +3 -0
  14. package/dist/oauth/strategy/index.js +49 -3
  15. package/dist/oauth/utilities/clearCookie.d.ts +1 -0
  16. package/dist/oauth/utilities/clearCookie.js +13 -9
  17. package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
  18. package/dist/oauth/utilities/clearSessionCookies.js +17 -0
  19. package/dist/oauth/utilities/mergeHeaders.js +11 -23
  20. package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
  21. package/dist/oauth/utilities/refreshTokens.js +45 -34
  22. package/dist/plugin/build-config.js +8 -7
  23. package/dist/plugin/dev-cookie-names.d.ts +4 -1
  24. package/dist/plugin/dev-cookie-names.js +6 -3
  25. package/dist/plugin/environment-error.d.ts +4 -0
  26. package/dist/plugin/environment-error.js +22 -0
  27. package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
  28. package/dist/plugin/sandbox-upload-fetch.js +22 -14
  29. package/dist/storage-content-api/client.d.ts +3 -3
  30. package/dist/storage-content-api/client.js +13 -35
  31. package/dist/storage-content-api/index.js +20 -21
  32. package/dist/storage-content-api/staticHandler.js +4 -1
  33. package/dist/storage-content-api/types.d.ts +2 -2
  34. package/dist/utils/env-management.js +7 -0
  35. package/package.json +1 -1
  36. package/dist/db-content-api/utilities/auth.d.ts +0 -29
  37. package/dist/db-content-api/utilities/auth.js +0 -82
@@ -19,7 +19,8 @@ export declare const LAMBDA_MAX_UNZIPPED_BYTES: number;
19
19
  *
20
20
  * @param projectPath - Path to project root
21
21
  * @returns The built bundle: its unzipped byte size and the absolute zip path.
22
- * @throws Error if standalone directory missing or zip creation fails
22
+ * @throws Error if standalone directory missing, the build embeds an undeployable Server
23
+ * Actions key, or zip creation fails
23
24
  */
24
25
  export declare function buildLambdaZip(projectPath: string, output?: string, options?: {
25
26
  logger?: AdapterLogger;
@@ -3,6 +3,7 @@ import { createWriteStream } from 'fs';
3
3
  import fs from 'fs/promises';
4
4
  import path from 'path';
5
5
  import { configureNextjsCache } from './configureNextjsCache.js';
6
+ import { assertDeployableServerActionsKey } from './deploy-output/assertDeployableServerActionsKey.js';
6
7
  import { inspectNextjsOutput } from './deploy-output/inspectNextjsOutput.js';
7
8
  import { resolveOutputPath } from './deploy-output/resolveOutputPath.js';
8
9
  import { walkBundleFiles } from './fs-utils.js';
@@ -26,13 +27,15 @@ import { isBundlableFile } from './secret-files.js';
26
27
  *
27
28
  * @param projectPath - Path to project root
28
29
  * @returns The built bundle: its unzipped byte size and the absolute zip path.
29
- * @throws Error if standalone directory missing or zip creation fails
30
+ * @throws Error if standalone directory missing, the build embeds an undeployable Server
31
+ * Actions key, or zip creation fails
30
32
  */ export async function buildLambdaZip(projectPath, output, options = {}) {
31
33
  const outputPath = resolveOutputPath(projectPath, 'nextjs', output);
32
34
  const layout = await inspectNextjsOutput(outputPath);
33
35
  if (!layout) {
34
36
  throw new Error(`Standalone build not found at ${outputPath}`);
35
37
  }
38
+ await assertDeployableServerActionsKey(outputPath);
36
39
  const files = (await walkBundleFiles(layout.standalonePath)).filter((file)=>isBundlableFile(file.relativePath));
37
40
  // Override archive entries in memory without changing Next's standalone output.
38
41
  const bundleFileOverrides = await createBundleFileOverrides(layout.standalonePath, layout.serverEntryPath, options.logger);
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Throws when a Next.js build output embeds a Server Actions key that must not
3
+ * be deployed.
4
+ *
5
+ * Next writes the key to `server/server-reference-manifest.json`, and the
6
+ * deployed server uses it to encrypt the values Server Actions close over.
7
+ * Next does not validate a key supplied through
8
+ * `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY`, so a malformed one only fails at
9
+ * runtime. Reproducible builds may pin it to a public sentinel such as
10
+ * `AAAA…=` (32 zero bytes), which is safe for testing but publishes the key if
11
+ * deployed. A generated key never has every byte equal, so that is the
12
+ * sentinel test.
13
+ */
14
+ export declare function assertDeployableServerActionsKey(outputPath: string): Promise<void>;
@@ -0,0 +1,33 @@
1
+ import path from 'path';
2
+ import { readJson } from './readJson.js';
3
+ const AES_KEY_BYTE_LENGTHS = [
4
+ 16,
5
+ 24,
6
+ 32
7
+ ];
8
+ /**
9
+ * Throws when a Next.js build output embeds a Server Actions key that must not
10
+ * be deployed.
11
+ *
12
+ * Next writes the key to `server/server-reference-manifest.json`, and the
13
+ * deployed server uses it to encrypt the values Server Actions close over.
14
+ * Next does not validate a key supplied through
15
+ * `NEXT_SERVER_ACTIONS_ENCRYPTION_KEY`, so a malformed one only fails at
16
+ * runtime. Reproducible builds may pin it to a public sentinel such as
17
+ * `AAAA…=` (32 zero bytes), which is safe for testing but publishes the key if
18
+ * deployed. A generated key never has every byte equal, so that is the
19
+ * sentinel test.
20
+ */ export async function assertDeployableServerActionsKey(outputPath) {
21
+ const manifestPath = path.join(outputPath, 'server', 'server-reference-manifest.json');
22
+ const key = (await readJson(manifestPath))?.encryptionKey;
23
+ if (typeof key !== 'string') {
24
+ return;
25
+ }
26
+ const bytes = Buffer.from(key, 'base64');
27
+ if (bytes.toString('base64').replace(/=+$/, '') !== key.replace(/=+$/, '') || !AES_KEY_BYTE_LENGTHS.includes(bytes.length)) {
28
+ throw new Error(`Refusing to deploy: the Server Actions encryptionKey in ${manifestPath} is not a base64-encoded 16, 24, or 32 byte AES key.`);
29
+ }
30
+ if (bytes.every((byte)=>byte === bytes[0])) {
31
+ throw new Error(`Refusing to deploy: ${manifestPath} embeds a sentinel Server Actions encryptionKey. ` + 'Rebuild with a secret NEXT_SERVER_ACTIONS_ENCRYPTION_KEY, or unset it so Next generates one.');
32
+ }
33
+ }
@@ -4,10 +4,12 @@ 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 { createContentApiClient } from '../content-api/createContentApiClient.js';
7
8
  import { buildDocumentSchema } from '../db-content-api/utilities/schema/buildDocumentSchema.js';
8
9
  import { cacheAllEnvironments } from '../utils/cache-bootstrap.js';
9
10
  import { getEnvVar } from '../utils/env-management.js';
10
11
  import { loadPayloadConfig } from '../utils/load-payload-config.js';
12
+ import { warning } from '../utils/log.js';
11
13
  import { resolveEnvironment } from '../utils/resolve-environment.js';
12
14
  import { loginCommand } from './login.js';
13
15
  /** Upload the current Payload collection schema for Content API migration tooling. */ export async function uploadSchemaCommand(options = {}) {
@@ -46,15 +48,24 @@ import { loginCommand } from './login.js';
46
48
  const documentSchema = buildDocumentSchema(config);
47
49
  spinner.message('Uploading collection schema...');
48
50
  const apiKey = process.env.FIGMA_CONTENT_API_ACCESS_KEY;
49
- const projectToken = apiKey ? null : await getValidProjectToken({
51
+ const auth = apiKey ? {
52
+ apiKey,
53
+ mode: 'apiKey'
54
+ } : {
55
+ mode: 'tokenStore',
50
56
  projectInfo: {
51
57
  environmentName: environment.name,
52
58
  projectId
53
59
  },
60
+ tokenStore
61
+ };
62
+ // Preserve the CLI's auth error before URL validation. The client reuses the cached token.
63
+ const tokenStoreMissingTokenCheck = auth.mode === 'tokenStore' && !await getValidProjectToken({
64
+ projectInfo: auth.projectInfo,
54
65
  tenantId: environment.contentSystemId,
55
66
  tokenStore
56
67
  });
57
- if (!apiKey && !projectToken) {
68
+ if (tokenStoreMissingTokenCheck) {
58
69
  throw new Error('Could not get a project token. Run `@payloadcms/figma login` and retry.');
59
70
  }
60
71
  // The bootstrap environment carries its regional Content API URL.
@@ -62,17 +73,20 @@ import { loginCommand } from './login.js';
62
73
  if (!contentApiUrl) {
63
74
  throw new Error(`No Content API URL returned for environment "${environment.name}".`);
64
75
  }
65
- const response = await fetch(`${contentApiUrl}/api/v0/content_systems/${encodeURIComponent(environment.contentSystemId)}/jsonb_to_index_migration_schema`, {
76
+ const contentApi = createContentApiClient({
77
+ auth,
78
+ baseUrl: contentApiUrl,
79
+ contentSystemId: environment.contentSystemId,
80
+ logger: {
81
+ warn: warning
82
+ }
83
+ });
84
+ const response = await contentApi.request(`/api/v0/content_systems/${encodeURIComponent(environment.contentSystemId)}/jsonb_to_index_migration_schema`, {
66
85
  body: JSON.stringify({
67
86
  documentSchema
68
87
  }),
69
88
  headers: {
70
- 'Content-Type': 'application/json',
71
- ...apiKey ? {
72
- 'X-Api-Key': apiKey
73
- } : {
74
- Authorization: `Bearer ${projectToken}`
75
- }
89
+ 'Content-Type': 'application/json'
76
90
  },
77
91
  method: 'PUT'
78
92
  });
@@ -1,3 +1,4 @@
1
+ import { isDeepStrictEqual } from 'node:util';
1
2
  import { APIError, createDatabaseAdapter, ValidationError } from 'payload';
2
3
  import { v4 as uuid } from 'uuid';
3
4
  import { FigmaApiError } from '../api/figma-api.js';
@@ -572,7 +573,43 @@ export function getClearDatabaseUrl(url, cutoverState) {
572
573
  }
573
574
  return clearDatabaseUrl.toString();
574
575
  }
576
+ async function countJobsForHandleSchedules(args) {
577
+ if (args.collection !== 'payload-jobs') {
578
+ return undefined;
579
+ }
580
+ // Payload's /handle-schedules counts unfinished jobs before queuing another occurrence.
581
+ // Until v1 supports error and meta.scheduled JSON filters, apply those filters locally.
582
+ const countFilters = args.where?.and ?? [];
583
+ const noErrorFilter = countFilters.find((filter)=>isDeepStrictEqual(filter, {
584
+ error: {
585
+ exists: false
586
+ }
587
+ }));
588
+ if (!noErrorFilter) {
589
+ return undefined;
590
+ }
591
+ const onlyScheduledJobsFilter = countFilters.find((filter)=>isDeepStrictEqual(filter, {
592
+ 'meta.scheduled': {
593
+ equals: true
594
+ }
595
+ }));
596
+ const { docs } = await this.find({
597
+ ...args,
598
+ limit: 0,
599
+ where: {
600
+ ...args.where,
601
+ and: countFilters.filter((filter)=>filter !== noErrorFilter && filter !== onlyScheduledJobsFilter)
602
+ }
603
+ });
604
+ return {
605
+ totalDocs: docs.filter((job)=>job.error == null && (!onlyScheduledJobsFilter || job.meta?.scheduled === true)).length
606
+ };
607
+ }
575
608
  async function count(args) {
609
+ const handleSchedulesCount = await countJobsForHandleSchedules.call(this, args);
610
+ if (handleSchedulesCount) {
611
+ return handleSchedulesCount;
612
+ }
576
613
  const locale = addFallbackLocale(args.locale, this.payload);
577
614
  const { data: response, error, response: httpResponse } = await this.client.POST('/api/v1/documents:count', {
578
615
  body: {
package/dist/index.d.ts CHANGED
@@ -4,4 +4,5 @@ export { figmaContentSystem } from './plugin/adapter.js';
4
4
  export type { FigmaContentSystemOptions } from './plugin/adapter.js';
5
5
  export { buildFigmaConfig } from './plugin/build-config.js';
6
6
  export type { FigmaConfig } from './plugin/build-config.js';
7
+ export { FigmaEnvironmentError } from './plugin/environment-error.js';
7
8
  export { passesMakeViewerWriteGate } from './plugin/make-permission-access/make-permission-access.js';
package/dist/index.js CHANGED
@@ -4,5 +4,6 @@ export { contentAPIAdapter } from './db-content-api/index.js';
4
4
  export { figmaContentSystem } from './plugin/adapter.js';
5
5
  // Export buildConfig wrapper and its config type
6
6
  export { buildFigmaConfig } from './plugin/build-config.js';
7
+ export { FigmaEnvironmentError } from './plugin/environment-error.js';
7
8
  // Export the Make permission predicate for slug-specific baseAccess overrides.
8
9
  export { passesMakeViewerWriteGate } from './plugin/make-permission-access/make-permission-access.js';
@@ -1,4 +1,5 @@
1
- import { type CollectionMeHook } from 'payload';
2
- export declare const getMeHook: ({ cookieName }: {
3
- cookieName: string;
1
+ import type { CollectionMeHook } from 'payload';
2
+ import type { Strategy } from '../strategy/index.js';
3
+ export declare const getMeHook: ({ strategy }: {
4
+ strategy: Strategy;
4
5
  }) => CollectionMeHook;
@@ -1,53 +1,7 @@
1
- import { parseCookies } from 'payload';
2
- import { createDebugLogger } from '../utilities/createDebugLogger.js';
3
- import { getTokenExp } from '../utilities/getTokenExp.js';
4
- export const getMeHook = ({ cookieName })=>// eslint-disable-next-line @typescript-eslint/require-await
5
- async ({ args, user })=>{
6
- const debugLogger = createDebugLogger(args.req.payload, false);
7
- const cookies = parseCookies(args.req.headers);
8
- const refreshToken = cookies.get(`${cookieName}-refresh`);
9
- let token = cookies.get(cookieName);
10
- let exp;
11
- if (refreshToken) {
12
- exp = getTokenExp({
13
- debugLogger,
14
- token: refreshToken
15
- });
16
- if (exp) {
17
- return {
18
- exp,
19
- user
20
- };
21
- }
22
- }
23
- if (!token) {
24
- // Parse Authorization header if exists
25
- const jwtFromHeader = args.req.headers.get('authorization');
26
- if (typeof jwtFromHeader === 'string' && jwtFromHeader.startsWith('Bearer ')) {
27
- token = jwtFromHeader.replace('Bearer ', '');
28
- exp = getTokenExp({
29
- debugLogger,
30
- token
31
- });
32
- if (exp) {
33
- return {
34
- exp,
35
- user
36
- };
37
- }
38
- }
39
- }
40
- if (token) {
41
- exp = getTokenExp({
42
- debugLogger,
43
- token
44
- });
45
- if (exp) {
46
- return {
47
- exp,
48
- user
49
- };
50
- }
51
- }
52
- return undefined;
1
+ export const getMeHook = ({ strategy })=>({ args, user })=>{
2
+ const exp = strategy.authenticatedTokenExpirations.get(args.req.headers);
3
+ return exp === undefined ? undefined : {
4
+ exp,
5
+ user
6
+ };
53
7
  };
@@ -1,5 +1,6 @@
1
1
  import jwt from 'jsonwebtoken';
2
2
  import { generateCookie, parseCookies } from 'payload';
3
+ import { clearSessionCookies } from '../utilities/clearSessionCookies.js';
3
4
  import { createCookieOptions } from '../utilities/createCookieOptions.js';
4
5
  import { createDebugLogger } from '../utilities/createDebugLogger.js';
5
6
  import { getCookieExpiration } from '../utilities/getCookieExpiration.js';
@@ -69,11 +70,18 @@ export const getRefreshHook = ({ pluginOptions, strategy })=>async ({ args, user
69
70
  return undefined;
70
71
  }
71
72
  const result = await refreshTokens({
73
+ headers: args.req.headers,
72
74
  payload: args.req.payload,
73
75
  refreshToken,
74
76
  strategy
75
77
  });
76
- if (!result) {
78
+ if (result.status !== 'success') {
79
+ if (result.status === 'rejected') {
80
+ mergeHeaders(clearSessionCookies({
81
+ headers: args.req.headers,
82
+ strategy
83
+ }), args.req.responseHeaders);
84
+ }
77
85
  return undefined;
78
86
  }
79
87
  mergeHeaders(result.headers, args.req.responseHeaders);
@@ -225,7 +225,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
225
225
  // Do not inject the me hook if the usePayloadJWT option is enabled
226
226
  ...!collectionOptions.usePayloadJWT ? [
227
227
  getMeHook({
228
- cookieName
228
+ strategy
229
229
  })
230
230
  ] : []
231
231
  ],
@@ -14,6 +14,8 @@ export interface Options {
14
14
  verify: VerifyFunction;
15
15
  }
16
16
  export declare class Strategy {
17
+ /** Keeps /me aligned with authentication-time renewal without changing request cookies. */
18
+ authenticatedTokenExpirations: WeakMap<Headers, number | undefined>;
17
19
  clientID: string;
18
20
  collection: CollectionConfig;
19
21
  collectionOptions: CollectionOptions;
@@ -38,6 +40,7 @@ export declare class Strategy {
38
40
  pluginOptions: PluginOptions;
39
41
  verify: VerifyFunction;
40
42
  constructor(options: Options);
43
+ private setTokenExpiration;
41
44
  authenticate({ canSetHeaders, headers, payload, }: AuthStrategyFunctionArgs): Promise<AuthStrategyResult>;
42
45
  ensureMeta(): Promise<void>;
43
46
  fetchMeta(): Promise<void>;
@@ -2,11 +2,13 @@ import * as jose from 'jose';
2
2
  import { APIError, parseCookies } from 'payload';
3
3
  import { JWTValidationError, validatePayloadAdminToken } from '../../auth/jwt-validator.js';
4
4
  import { getInfraEnvironment } from '../../constants.js';
5
+ import { clearSessionCookies } from '../utilities/clearSessionCookies.js';
5
6
  import { createDebugLogger } from '../utilities/createDebugLogger.js';
6
7
  import { getTokenExp } from '../utilities/getTokenExp.js';
7
8
  import { mergeHeaders } from '../utilities/mergeHeaders.js';
8
9
  import { refreshTokens } from '../utilities/refreshTokens.js';
9
10
  export class Strategy {
11
+ /** Keeps /me aligned with authentication-time renewal without changing request cookies. */ authenticatedTokenExpirations = new WeakMap();
10
12
  clientID;
11
13
  collection;
12
14
  collectionOptions;
@@ -38,6 +40,11 @@ export class Strategy {
38
40
  // Prevent wokiness with `this`
39
41
  this.ensureMeta = this.ensureMeta.bind(this);
40
42
  }
43
+ setTokenExpiration({ exp, headers, verifyResult }) {
44
+ if (verifyResult.user) {
45
+ this.authenticatedTokenExpirations.set(headers, exp);
46
+ }
47
+ }
41
48
  async authenticate({ canSetHeaders, headers, payload }) {
42
49
  const debugLogger = createDebugLogger(payload, this.debug);
43
50
  await this.ensureMeta();
@@ -69,11 +76,13 @@ export class Strategy {
69
76
  msg: 'No access token found, but refresh token exists. Attempting to refresh...'
70
77
  });
71
78
  const refreshed = await refreshTokens({
79
+ headers,
72
80
  payload,
73
81
  refreshToken,
74
82
  strategy: this
75
83
  });
76
- if (refreshed) {
84
+ if (refreshed.status === 'success') {
85
+ const tokenExpiration = refreshed.decodedOauthToken.exp;
77
86
  const verifyResult = await this.verify({
78
87
  headers,
79
88
  payload,
@@ -83,6 +92,11 @@ export class Strategy {
83
92
  msg: 'Token refreshed. Verifying...',
84
93
  verifyResult
85
94
  });
95
+ this.setTokenExpiration({
96
+ exp: tokenExpiration,
97
+ headers,
98
+ verifyResult
99
+ });
86
100
  // Only return response headers (to set cookies) when canSetHeaders is true.
87
101
  // During RSC navigation, canSetHeaders=false because response streaming
88
102
  // has already started and cookies cannot be modified.
@@ -100,6 +114,15 @@ export class Strategy {
100
114
  user: verifyResult.user
101
115
  };
102
116
  } else {
117
+ if (refreshed.status === 'rejected' && canSetHeaders) {
118
+ return {
119
+ responseHeaders: clearSessionCookies({
120
+ headers,
121
+ strategy: this
122
+ }),
123
+ user: null
124
+ };
125
+ }
103
126
  debugLogger.info({
104
127
  msg: 'Token refresh failed'
105
128
  });
@@ -126,6 +149,7 @@ export class Strategy {
126
149
  // but first set exp from refresh token
127
150
  // because access exp is likely very short lived
128
151
  if (typeof oauthTokenVerifyResult === 'object' && !(oauthTokenVerifyResult instanceof Error)) {
152
+ const tokenExpiration = oauthTokenVerifyResult.exp;
129
153
  if (refreshToken) {
130
154
  const refreshTokenExp = getTokenExp({
131
155
  debugLogger,
@@ -135,11 +159,17 @@ export class Strategy {
135
159
  oauthTokenVerifyResult.exp = refreshTokenExp;
136
160
  }
137
161
  }
138
- return this.verify({
162
+ const verifyResult = await this.verify({
139
163
  headers,
140
164
  payload,
141
165
  token: oauthTokenVerifyResult
142
166
  });
167
+ this.setTokenExpiration({
168
+ exp: tokenExpiration,
169
+ headers,
170
+ verifyResult
171
+ });
172
+ return verifyResult;
143
173
  }
144
174
  }
145
175
  // Handle expired access token with valid refresh token.
@@ -147,6 +177,7 @@ export class Strategy {
147
177
  // but only update cookies when canSetHeaders=true.
148
178
  if (oauthTokenVerifyResult instanceof JWTValidationError && oauthTokenVerifyResult.code === 'EXPIRED' && refreshToken && !this.collectionOptions.usePayloadJWT) {
149
179
  const refreshed = await refreshTokens({
180
+ headers,
150
181
  payload,
151
182
  refreshToken,
152
183
  strategy: this
@@ -154,7 +185,8 @@ export class Strategy {
154
185
  debugLogger.info({
155
186
  msg: 'Token expired. Refreshing...'
156
187
  });
157
- if (refreshed) {
188
+ if (refreshed.status === 'success') {
189
+ const tokenExpiration = refreshed.decodedOauthToken.exp;
158
190
  const verifyResult = await this.verify({
159
191
  headers,
160
192
  payload,
@@ -164,6 +196,11 @@ export class Strategy {
164
196
  msg: 'Token refreshed. Verifying...',
165
197
  verifyResult
166
198
  });
199
+ this.setTokenExpiration({
200
+ exp: tokenExpiration,
201
+ headers,
202
+ verifyResult
203
+ });
167
204
  if (canSetHeaders) {
168
205
  if (verifyResult.responseHeaders) {
169
206
  mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
@@ -178,6 +215,15 @@ export class Strategy {
178
215
  user: verifyResult.user
179
216
  };
180
217
  } else {
218
+ if (refreshed.status === 'rejected' && canSetHeaders) {
219
+ return {
220
+ responseHeaders: clearSessionCookies({
221
+ headers,
222
+ strategy: this
223
+ }),
224
+ user: null
225
+ };
226
+ }
181
227
  debugLogger.info({
182
228
  msg: 'Token refresh failed'
183
229
  });
@@ -6,3 +6,4 @@ export declare const clearCookie: (args: {
6
6
  overrides?: Partial<CookieOptions>;
7
7
  req: PayloadRequest;
8
8
  }) => void;
9
+ export declare const generateClearedCookie: (cookieName: string, cookieOptions: CookieOptions) => string;
@@ -1,23 +1,27 @@
1
1
  import { generateCookie } from 'payload';
2
- import { getCookieExpiration } from './getCookieExpiration.js';
3
2
  import { withPartitionedCookie } from './withPartitionedCookie.js';
4
3
  export const clearCookie = (args)=>{
5
4
  const options = {
6
5
  ...args.cookieOptions,
7
6
  ...args.overrides || {}
8
7
  };
9
- const clearedCookie = generateCookie({
10
- ...options,
11
- name: args.cookieName,
12
- expires: getCookieExpiration(options?.expires) ?? new Date(),
13
- returnCookieAsObject: false,
14
- value: ''
15
- });
8
+ const clearedCookie = generateClearedCookie(args.cookieName, options);
16
9
  if (!args.req.responseHeaders) {
17
10
  args.req.responseHeaders = new Headers();
18
11
  }
19
12
  // Match the Partitioned attribute the cookie was set with — a Max-Age=0 clear
20
13
  // without it targets the unpartitioned jar and won't delete the partitioned
21
14
  // cookie, so logout wouldn't clear the session in the cross-site Make iframe.
22
- args.req.responseHeaders.append('Set-Cookie', withPartitionedCookie(clearedCookie));
15
+ args.req.responseHeaders.append('Set-Cookie', clearedCookie);
16
+ };
17
+ export const generateClearedCookie = (cookieName, cookieOptions)=>{
18
+ const cookie = generateCookie({
19
+ ...cookieOptions,
20
+ name: cookieName,
21
+ expires: new Date(0),
22
+ maxAge: 0,
23
+ returnCookieAsObject: false,
24
+ value: ''
25
+ });
26
+ return withPartitionedCookie(cookie);
23
27
  };
@@ -0,0 +1,5 @@
1
+ import type { Strategy } from '../strategy/index.js';
2
+ export declare const clearSessionCookies: ({ headers, strategy, }: {
3
+ headers: Headers;
4
+ strategy: Strategy;
5
+ }) => Headers;
@@ -0,0 +1,17 @@
1
+ import { generateClearedCookie } from './clearCookie.js';
2
+ import { createCookieOptions } from './createCookieOptions.js';
3
+ export const clearSessionCookies = ({ headers, strategy })=>{
4
+ const cookieOptions = createCookieOptions({
5
+ collection: strategy.collection,
6
+ headers,
7
+ pluginOptions: strategy.pluginOptions
8
+ });
9
+ const responseHeaders = new Headers();
10
+ for (const name of [
11
+ strategy.cookieName,
12
+ `${strategy.cookieName}-refresh`
13
+ ]){
14
+ responseHeaders.append('Set-Cookie', generateClearedCookie(name, cookieOptions));
15
+ }
16
+ return responseHeaders;
17
+ };
@@ -1,35 +1,23 @@
1
1
  const headersToJoin = [
2
- 'set-cookie',
3
2
  'warning',
4
3
  'www-authenticate',
5
4
  'proxy-authenticate',
6
5
  'vary'
7
6
  ];
8
7
  export function mergeHeaders(sourceHeaders, destinationHeaders) {
9
- // Create a map to store combined headers
10
- const combinedHeaders = new Headers();
11
- // Add existing destination headers to the combined map
12
- destinationHeaders.forEach((value, key)=>{
13
- combinedHeaders.set(key, value);
14
- });
15
- // Add source headers to the combined map, joining specific headers
16
8
  sourceHeaders.forEach((value, key)=>{
17
- const lowerKey = key.toLowerCase();
18
- if (headersToJoin.includes(lowerKey)) {
19
- if (combinedHeaders.has(key)) {
20
- combinedHeaders.set(key, `${combinedHeaders.get(key)}, ${value}`);
21
- } else {
22
- combinedHeaders.set(key, value);
23
- }
9
+ if (key.toLowerCase() === 'set-cookie') {
10
+ return;
11
+ }
12
+ if (headersToJoin.includes(key.toLowerCase())) {
13
+ destinationHeaders.append(key, value);
24
14
  } else {
25
- combinedHeaders.set(key, value);
15
+ destinationHeaders.set(key, value);
26
16
  }
27
17
  });
28
- // Clear the destination headers and set the combined headers
29
- destinationHeaders.forEach((_, key)=>{
30
- destinationHeaders.delete(key);
31
- });
32
- combinedHeaders.forEach((value, key)=>{
33
- destinationHeaders.append(key, value);
34
- });
18
+ // Set-Cookie cannot be comma-joined: Expires contains commas, and each
19
+ // cookie must remain a separate header for browsers to apply both deletions.
20
+ for (const cookie of sourceHeaders.getSetCookie()){
21
+ destinationHeaders.append('Set-Cookie', cookie);
22
+ }
35
23
  }
@@ -2,14 +2,20 @@ import type jwt from 'jsonwebtoken';
2
2
  import type { Payload } from 'payload';
3
3
  import type { Strategy } from '../strategy/index.js';
4
4
  interface Args {
5
+ headers: Headers;
5
6
  payload: Payload;
6
7
  refreshToken: string;
7
8
  strategy: Strategy;
8
9
  }
9
- type Result = {
10
+ export type RefreshResult = {
10
11
  decodedOauthToken: jwt.JwtPayload;
11
12
  headers: Headers;
13
+ status: 'success';
12
14
  token: string;
13
- } | false;
14
- export declare const refreshTokens: ({ payload, refreshToken, strategy }: Args) => Promise<Result>;
15
+ } | {
16
+ status: 'rejected';
17
+ } | {
18
+ status: 'temporary_failure';
19
+ };
20
+ export declare const refreshTokens: ({ headers: requestHeaders, payload, refreshToken, strategy, }: Args) => Promise<RefreshResult>;
15
21
  export {};
@@ -1,20 +1,19 @@
1
1
  import { generateCookie } from 'payload';
2
- import { getPayloadAdminToken } from '../../api/figma-api.js';
2
+ import { FigmaApiError, getPayloadAdminToken } from '../../api/figma-api.js';
3
3
  import { validatePayloadAdminToken } from '../../auth/jwt-validator.js';
4
4
  import { getInfraEnvironment } from '../../constants.js';
5
5
  import { createCookieOptions } from './createCookieOptions.js';
6
6
  import { createDebugLogger } from './createDebugLogger.js';
7
7
  import { getCookieExpiration } from './getCookieExpiration.js';
8
8
  import { withPartitionedCookie } from './withPartitionedCookie.js';
9
- export const refreshTokens = async ({ payload, refreshToken, strategy })=>{
9
+ export const refreshTokens = async ({ headers: requestHeaders, payload, refreshToken, strategy })=>{
10
10
  const debugLogger = createDebugLogger(payload, strategy.debug);
11
11
  debugLogger.info({
12
12
  msg: 'Refreshing tokens'
13
13
  });
14
14
  const headers = new Headers();
15
- // At this point, access token is expired
16
- // but refresh token is still valid
17
- // so we will refresh both tokens
15
+ // The refresh cookie holds an OAuth access token. Use it to mint a new
16
+ // session JWT; this does not rotate an OAuth refresh token.
18
17
  try {
19
18
  // Get another Payload Admin token.
20
19
  const environmentId = payload.config.custom.figma.environmentId;
@@ -34,42 +33,54 @@ export const refreshTokens = async ({ payload, refreshToken, strategy })=>{
34
33
  debugLogger.error({
35
34
  msg: 'Error refreshing tokens'
36
35
  });
37
- return false;
38
- }
39
- if (token) {
40
- debugLogger.info({
41
- msg: 'Successfully refreshed Payload Admin token'
42
- });
43
- const expires_in = new Date(expiresAt);
44
- const cookieOptions = createCookieOptions({
45
- collection: strategy.collection,
46
- headers,
47
- pluginOptions: strategy.pluginOptions
48
- });
49
- const tokenCookie = generateCookie({
50
- ...cookieOptions,
51
- name: strategy.cookieName,
52
- expires: getCookieExpiration(expires_in),
53
- returnCookieAsObject: false,
54
- value: token
55
- });
56
- headers.append('Set-Cookie', withPartitionedCookie(tokenCookie));
57
- const decodedOauthToken = await validatePayloadAdminToken({
58
- audience: environmentId,
59
- environment: getInfraEnvironment(),
60
- token
61
- });
62
36
  return {
63
- decodedOauthToken,
64
- headers,
65
- token
37
+ status: 'temporary_failure'
66
38
  };
67
39
  }
40
+ debugLogger.info({
41
+ msg: 'Successfully refreshed Payload Admin token'
42
+ });
43
+ const decodedOauthToken = await validatePayloadAdminToken({
44
+ audience: environmentId,
45
+ environment: getInfraEnvironment(),
46
+ token
47
+ });
48
+ const expires_in = new Date(expiresAt);
49
+ const cookieOptions = createCookieOptions({
50
+ collection: strategy.collection,
51
+ headers: requestHeaders,
52
+ pluginOptions: strategy.pluginOptions
53
+ });
54
+ const tokenCookie = generateCookie({
55
+ ...cookieOptions,
56
+ name: strategy.cookieName,
57
+ expires: getCookieExpiration(expires_in),
58
+ returnCookieAsObject: false,
59
+ value: token
60
+ });
61
+ headers.append('Set-Cookie', withPartitionedCookie(tokenCookie));
62
+ return {
63
+ decodedOauthToken,
64
+ headers,
65
+ status: 'success',
66
+ token
67
+ };
68
68
  } catch (error) {
69
+ if (error instanceof FigmaApiError && [
70
+ 401,
71
+ 403,
72
+ 404
73
+ ].includes(error.statusCode ?? 0)) {
74
+ return {
75
+ status: 'rejected'
76
+ };
77
+ }
69
78
  debugLogger.error({
70
79
  err: error,
71
80
  msg: 'Error refreshing tokens'
72
81
  });
73
82
  }
74
- return false;
83
+ return {
84
+ status: 'temporary_failure'
85
+ };
75
86
  };
@@ -23,6 +23,7 @@ import { logMissingContentSystemId } from './bootstrap-preflight.js';
23
23
  import { createCacheRevalidationHooksPlugin } from './cache-revalidation-hooks.js';
24
24
  import { LIMIT_REACHED_VIEW_KEY, LIMIT_REACHED_VIEW_PATH } from './cloud-limits/routes.js';
25
25
  import { getDevCookieNames } from './dev-cookie-names.js';
26
+ import { FigmaEnvironmentError } from './environment-error.js';
26
27
  import { passesMakeViewerWriteGate, withMakeViewerWriteBaseAccessDefaults } from './make-permission-access/make-permission-access.js';
27
28
  import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
28
29
  /**
@@ -200,18 +201,18 @@ function readCachedBootstrapData() {
200
201
  }
201
202
  const scope = readProjectScope();
202
203
  if (!scope) {
203
- throw new Error('Could not resolve the Content API URL.');
204
+ throw new FigmaEnvironmentError('Could not resolve the Content API URL.');
204
205
  }
205
206
  const message = `Could not resolve the Content API URL for environment "${scope.environmentName}" of project ${scope.projectId}.`;
206
207
  if (args.bootstrapFetched) {
207
- throw new Error(message);
208
+ throw new FigmaEnvironmentError(message);
208
209
  }
209
210
  const resolution = await resolveAndCacheBootstrap(getTokenStore(), scope.projectId, scope.environmentName);
210
211
  if (!resolution.ok) {
211
- throw new Error(`${message} ${describeBootstrapFailure(resolution.reason)}`);
212
+ throw new FigmaEnvironmentError(`${message} ${describeBootstrapFailure(resolution.reason)}`);
212
213
  }
213
214
  if (!resolution.data.contentApiUrl) {
214
- throw new Error(message);
215
+ throw new FigmaEnvironmentError(message);
215
216
  }
216
217
  return resolution.data.contentApiUrl;
217
218
  }
@@ -365,13 +366,13 @@ export async function buildFigmaConfig(config) {
365
366
  environmentId = bootstrapData?.tenantInstanceId;
366
367
  }
367
368
  if (!environmentId) {
368
- throw new Error('Environment ID could not be resolved. Set FIGMA_EID or initialize the project.');
369
+ throw new FigmaEnvironmentError('Environment ID could not be resolved. Set FIGMA_EID or initialize the project.');
369
370
  }
370
371
  if (!contentSystemId) {
371
372
  logMissingContentSystemId(bootstrapReason ?? {
372
373
  kind: 'no-config'
373
374
  });
374
- throw new Error('Content System ID could not be resolved. ' + 'Run `npx @payloadcms/figma init` to set up your project.');
375
+ throw new FigmaEnvironmentError('Content System ID could not be resolved. ' + 'Run `npx @payloadcms/figma init` to set up your project.');
375
376
  }
376
377
  // Only the content-system db adapter and cloud storage call the Content API, so a project on a
377
378
  // custom db with storage disabled needs no URL; `url` stays '' and is unused in that case.
@@ -560,7 +561,7 @@ export async function buildFigmaConfig(config) {
560
561
  usernameField: 'email'
561
562
  }
562
563
  ],
563
- ...isProduction ? {} : getDevCookieNames(contentSystemId),
564
+ ...isProduction ? {} : getDevCookieNames(contentSystemId, config.cookiePrefix),
564
565
  debug: !!process.env.DEBUG,
565
566
  disabled: false
566
567
  }),
@@ -5,9 +5,12 @@
5
5
  * switching environments in the same checkout; falls back to contentSystemId
6
6
  * when projectId isn't in `.env`.
7
7
  *
8
+ * Names must start with `cookiePrefix`: Payload forwards every other request
9
+ * cookie when it fetches an external upload URL.
10
+ *
8
11
  * In production, cookies are isolated by unique hostnames and this is unused.
9
12
  */
10
- export declare function getDevCookieNames(contentSystemId: string): {
13
+ export declare function getDevCookieNames(contentSystemId: string, cookiePrefix?: string): {
11
14
  cookieName: string;
12
15
  userInfoCookieName: string;
13
16
  };
@@ -6,12 +6,15 @@ import { getEnvVarSync } from '../utils/env-management.js';
6
6
  * switching environments in the same checkout; falls back to contentSystemId
7
7
  * when projectId isn't in `.env`.
8
8
  *
9
+ * Names must start with `cookiePrefix`: Payload forwards every other request
10
+ * cookie when it fetches an external upload URL.
11
+ *
9
12
  * In production, cookies are isolated by unique hostnames and this is unused.
10
- */ export function getDevCookieNames(contentSystemId) {
13
+ */ export function getDevCookieNames(contentSystemId, cookiePrefix = 'payload') {
11
14
  const projectId = process.env.FIGMA_PROJECT_ID ?? getEnvVarSync(process.cwd(), 'FIGMA_PROJECT_ID') ?? contentSystemId;
12
15
  const suffix = projectId.slice(0, 8);
13
16
  return {
14
- cookieName: `figma-${suffix}-oauth-token`,
15
- userInfoCookieName: `figma-${suffix}-user-info`
17
+ cookieName: `${cookiePrefix}-figma-${suffix}-oauth-token`,
18
+ userInfoCookieName: `${cookiePrefix}-figma-${suffix}-user-info`
16
19
  };
17
20
  }
@@ -0,0 +1,4 @@
1
+ /** Required Figma environment configuration could not be resolved. */
2
+ export declare class FigmaEnvironmentError extends Error {
3
+ name: string;
4
+ }
@@ -0,0 +1,22 @@
1
+ import * as payload from 'payload';
2
+ /** Required Figma environment configuration could not be resolved. */ export class FigmaEnvironmentError extends Error {
3
+ name = 'FigmaEnvironmentError';
4
+ }
5
+ // Older Payload versions do not expose a CLI error hook and retain their default status 1.
6
+ if ('registerCLIExitCodeHandler' in payload && typeof payload.registerCLIExitCodeHandler === 'function') {
7
+ payload.registerCLIExitCodeHandler({
8
+ handler: (error)=>{
9
+ if (!(error instanceof FigmaEnvironmentError)) {
10
+ return undefined;
11
+ }
12
+ // Figma environments inject this status so the platform can detect
13
+ // and classify environment misconfigurations.
14
+ const rawExitCode = process.env.FIGMA_DEPLOY_FAILURE_EXIT_CODE;
15
+ if (rawExitCode === undefined || !/^\d+$/.test(rawExitCode)) {
16
+ return undefined;
17
+ }
18
+ const exitCode = Number(rawExitCode);
19
+ return exitCode >= 1 && exitCode <= 255 ? exitCode : undefined;
20
+ }
21
+ });
22
+ }
@@ -19,14 +19,13 @@ type SandboxUploadFetchOptions = {
19
19
  * maps external hostnames to unique-local IPv6 addresses (`fc00::/7`) that
20
20
  * `safeFetch` rejects as non-unicast. A no-op elsewhere.
21
21
  *
22
- * Only a default: a collection that set `skipSafeFetch` itself keeps its value.
23
- * `externalFileHeaderFilter` is left unset on purpose, since it would replace
24
- * the cookie logic that forwards credentials for relative URLs.
22
+ * A collection that sets `skipSafeFetch` keeps its value.
23
+ * The default header filter removes current and legacy OAuth cookies from
24
+ * external requests. Trusted same-origin relative URLs retain their cookies.
25
25
  *
26
26
  * SSRF risks, bounded by the routes' auth gate and sandbox network limits:
27
- * `getExternalFile` re-validates redirects only against `pasteURL.allowList`,
28
- * any session can GET an arbitrary URL and read the body, and request cookies
29
- * reach the target.
27
+ * Payload checks each redirect against `pasteURL.allowList`.
28
+ * An authenticated session can fetch an arbitrary URL and read its body.
30
29
  */
31
30
  export declare function createSandboxUploadFetchPlugin({ userCollections }: SandboxUploadFetchOptions): (config: Config) => Config;
32
31
  export {};
@@ -12,14 +12,13 @@ import * as log from '../utils/log.js';
12
12
  * maps external hostnames to unique-local IPv6 addresses (`fc00::/7`) that
13
13
  * `safeFetch` rejects as non-unicast. A no-op elsewhere.
14
14
  *
15
- * Only a default: a collection that set `skipSafeFetch` itself keeps its value.
16
- * `externalFileHeaderFilter` is left unset on purpose, since it would replace
17
- * the cookie logic that forwards credentials for relative URLs.
15
+ * A collection that sets `skipSafeFetch` keeps its value.
16
+ * The default header filter removes current and legacy OAuth cookies from
17
+ * external requests. Trusted same-origin relative URLs retain their cookies.
18
18
  *
19
19
  * SSRF risks, bounded by the routes' auth gate and sandbox network limits:
20
- * `getExternalFile` re-validates redirects only against `pasteURL.allowList`,
21
- * any session can GET an arbitrary URL and read the body, and request cookies
22
- * reach the target.
20
+ * Payload checks each redirect against `pasteURL.allowList`.
21
+ * An authenticated session can fetch an arbitrary URL and read its body.
23
22
  */ export function createSandboxUploadFetchPlugin({ userCollections }) {
24
23
  const appOwnedSlugs = new Set((userCollections ?? []).filter((collection)=>typeof collection.upload === 'object' && 'skipSafeFetch' in collection.upload).map((collection)=>collection.slug));
25
24
  return (config)=>{
@@ -27,27 +26,36 @@ import * as log from '../utils/log.js';
27
26
  return config;
28
27
  }
29
28
  const modifiedSlugs = [];
29
+ let modified = false;
30
30
  const collections = (config.collections ?? []).map((collection)=>{
31
- if (!collection.upload || appOwnedSlugs.has(collection.slug)) {
31
+ if (!collection.upload) {
32
32
  return collection;
33
33
  }
34
- modifiedSlugs.push(collection.slug);
34
+ modified = true;
35
+ if (!appOwnedSlugs.has(collection.slug)) {
36
+ modifiedSlugs.push(collection.slug);
37
+ }
35
38
  const upload = collection.upload === true ? {} : collection.upload;
36
39
  return {
37
40
  ...collection,
38
41
  upload: {
39
42
  ...upload,
40
- skipSafeFetch: true
43
+ ...!appOwnedSlugs.has(collection.slug) ? {
44
+ skipSafeFetch: true
45
+ } : {},
46
+ externalFileHeaderFilter: upload.externalFileHeaderFilter ?? ((headers, context)=>({
47
+ // Payload supplies fresh context for each redirect hop.
48
+ cookie: (headers.cookie ?? '').split(';').filter((cookie)=>context?.isSameOrigin || !cookie.trim().startsWith(config.cookiePrefix ?? 'payload') && !/^figma-.+-(?:oauth-token(?:-refresh)?|user-info)=/.test(cookie.trim())).join(';')
49
+ }))
41
50
  }
42
51
  };
43
52
  });
44
- if (modifiedSlugs.length === 0) {
45
- return config;
53
+ if (modified) {
54
+ log.debug(`Make sandbox detected: skipSafeFetch defaults applied (${modifiedSlugs.join(', ') || 'none'}); all upload collections default to forwarding CMS cookies only to trusted same-origin relative URLs. App-defined header filters are preserved.`);
46
55
  }
47
- log.debug(`Make sandbox detected: upload collections skip safeFetch (${modifiedSlugs.join(', ')})`);
48
- return {
56
+ return modified ? {
49
57
  ...config,
50
58
  collections
51
- };
59
+ } : config;
52
60
  };
53
61
  }
@@ -1,5 +1,5 @@
1
- import createClient from 'openapi-fetch';
2
1
  import type { UploadPaths } from './api-types.js';
3
2
  import type { StorageClientConfig } from './types.js';
4
- export type StorageClient = ReturnType<typeof createClient<UploadPaths>>;
5
- export declare function createStorageClient(config: StorageClientConfig): StorageClient;
3
+ import { createContentApiClient } from '../content-api/createContentApiClient.js';
4
+ export type StorageClient = ReturnType<typeof createContentApiClient<UploadPaths>>['api'];
5
+ export declare function createStorageClient(config: StorageClientConfig, warn?: (message: string) => void): StorageClient;
@@ -1,37 +1,15 @@
1
- import createClient from 'openapi-fetch';
2
- import { getValidProjectToken } from '../auth/project-token.js';
3
- import { fetchDevJwt } from '../db-content-api/utilities/auth.js';
4
- export function createStorageClient(config) {
5
- const client = createClient({
6
- baseUrl: config.baseUrl
7
- });
8
- client.use(createStorageAuthMiddleware(config));
9
- return client;
10
- }
11
- function createStorageAuthMiddleware(config) {
12
- return {
13
- async onRequest ({ request }) {
14
- if ('contentApiKey' in config) {
15
- request.headers.set('X-Api-Key', config.contentApiKey);
16
- } else {
17
- const { auth, contentSystemId } = config;
18
- if (auth.mode === 'apiKey') {
19
- request.headers.set('X-Api-Key', auth.apiKey);
20
- } else if (auth.mode === 'tokenStore') {
21
- const token = await getValidProjectToken({
22
- tenantId: contentSystemId,
23
- tokenStore: auth.tokenStore
24
- });
25
- if (!token) {
26
- throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.');
27
- }
28
- request.headers.set('Authorization', `Bearer ${token}`);
29
- } else {
30
- const token = await fetchDevJwt(config.baseUrl, contentSystemId);
31
- request.headers.set('Authorization', `Bearer ${token}`);
32
- }
33
- }
34
- return request;
1
+ import { createContentApiClient } from '../content-api/createContentApiClient.js';
2
+ import { warning } from '../utils/log.js';
3
+ export function createStorageClient(config, warn = warning) {
4
+ return createContentApiClient({
5
+ auth: 'contentApiKey' in config ? {
6
+ apiKey: config.contentApiKey,
7
+ mode: 'apiKey'
8
+ } : config.auth,
9
+ baseUrl: config.baseUrl,
10
+ contentSystemId: 'contentSystemId' in config ? config.contentSystemId : '',
11
+ logger: {
12
+ warn
35
13
  }
36
- };
14
+ }).api;
37
15
  }
@@ -7,37 +7,36 @@ import { getHandleUpload } from './handleUpload.js';
7
7
  import { getHandler } from './staticHandler.js';
8
8
  export function contentApiStorageAdapter(config) {
9
9
  return ({ collection, prefix })=>{
10
- const client = createStorageClient(config);
11
10
  const baseUrl = config.baseUrl;
12
- const deleteFile = getDeleteFile({
13
- client
14
- });
11
+ const deleteFile = (args)=>getDeleteFile({
12
+ client: createStorageClient(config, (message)=>args.req.payload.logger.warn(message))
13
+ })(args);
15
14
  return {
16
15
  name: 'content-api',
17
- copyFile: getCopyFile({
18
- client
19
- }),
16
+ copyFile: (args)=>getCopyFile({
17
+ client: createStorageClient(config, (message)=>args.req.payload.logger.warn(message))
18
+ })(args),
20
19
  deleteFile,
21
20
  generateURL: getGenerateURL({
22
21
  baseUrl
23
22
  }),
24
23
  handleDelete: deleteFile,
25
- handleUpload: getHandleUpload({
26
- client,
27
- collection
28
- }),
29
- staticHandler: getHandler({
30
- client,
31
- collection,
32
- prefix
33
- }),
24
+ handleUpload: (args)=>getHandleUpload({
25
+ client: createStorageClient(config, (message)=>args.req.payload.logger.warn(message)),
26
+ collection
27
+ })(args),
28
+ staticHandler: (req, args)=>getHandler({
29
+ client: createStorageClient(config, (message)=>req.payload.logger.warn(message)),
30
+ collection,
31
+ prefix
32
+ })(req, args),
34
33
  uploadInstructions: {
35
34
  enabled: true,
36
- generate: getGenerateUploadInstructions({
37
- access: config.uploadInstructionsAccess,
38
- client,
39
- collectionPrefix: prefix
40
- }),
35
+ generate: (args)=>getGenerateUploadInstructions({
36
+ access: config.uploadInstructionsAccess,
37
+ client: createStorageClient(config, (message)=>args.req.payload.logger.warn(message)),
38
+ collectionPrefix: prefix
39
+ })(args),
41
40
  requiresUploadReceipt: true,
42
41
  useInAdmin: true
43
42
  }
@@ -8,13 +8,16 @@ import { mediaErrorResponse } from './mediaErrorResponse.js';
8
8
  import { resolveDownloadResponseHeaders } from './resolveDownloadResponseHeaders.js';
9
9
  const PRESIGNED_DOWNLOAD_URL_EXPIRES_IN_SECONDS = 300;
10
10
  export const getHandler = ({ client, collection, prefix = '' })=>{
11
- return async (req, { doc, headers, params: { filename, operation, uploadReference } })=>{
11
+ return async (req, { doc, headers, params })=>{
12
+ const { filename, operation, uploadReference } = params;
13
+ const { isOriginal } = params;
12
14
  try {
13
15
  const prefixArgs = {
14
16
  collection,
15
17
  collectionPrefix: prefix,
16
18
  doc,
17
19
  filename,
20
+ isOriginal,
18
21
  req,
19
22
  uploadReference
20
23
  };
@@ -1,9 +1,9 @@
1
1
  import type { UploadInstructionsAccess } from 'payload';
2
- import type { AuthMode } from '../db-content-api/utilities/auth.js';
2
+ import type { ContentApiAuth } from '../content-api/auth.js';
3
3
  export type StorageClientConfig = {
4
4
  uploadInstructionsAccess?: UploadInstructionsAccess;
5
5
  } & ({
6
- auth: AuthMode;
6
+ auth: ContentApiAuth;
7
7
  baseUrl: string;
8
8
  contentSystemId: string;
9
9
  } | {
@@ -23,6 +23,11 @@ import path from 'path';
23
23
  }
24
24
  return null;
25
25
  }
26
+ function assertEnvVarPartHasNoLineTerminatorsOrNullBytes(part, input) {
27
+ if (/[\r\n\u2028\u2029\0]/u.test(input)) {
28
+ throw new Error(`Environment variable ${part} must not contain line terminators or null bytes`);
29
+ }
30
+ }
26
31
  /**
27
32
  * Get an environment variable value from .env file (async)
28
33
  *
@@ -70,6 +75,8 @@ import path from 'path';
70
75
  * @param key - Environment variable name
71
76
  * @param value - Environment variable value
72
77
  */ export async function addOrUpdateEnvVar(projectPath, key, value) {
78
+ assertEnvVarPartHasNoLineTerminatorsOrNullBytes('key', key);
79
+ assertEnvVarPartHasNoLineTerminatorsOrNullBytes('value', value);
73
80
  const envPath = path.join(projectPath, '.env');
74
81
  try {
75
82
  let contents = '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/figma",
3
- "version": "1.0.0-beta.1",
3
+ "version": "1.0.0-internal.d040868",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,29 +0,0 @@
1
- import type { Middleware } from 'openapi-fetch';
2
- import type { Payload } from 'payload';
3
- import type { TokenStore } from '../../auth/token-store.js';
4
- type ApiKeyAuth = {
5
- apiKey: string;
6
- mode: 'apiKey';
7
- };
8
- type TokenStoreAuth = {
9
- mode: 'tokenStore';
10
- tokenStore: TokenStore;
11
- };
12
- type DevJwtAuth = {
13
- mode: 'devJwt';
14
- };
15
- export type AuthMode = ApiKeyAuth | DevJwtAuth | TokenStoreAuth;
16
- export declare function fetchDevJwt(url: string, contentSystemId: string): Promise<string>;
17
- export declare function createAuthMiddleware(opts: {
18
- auth: AuthMode;
19
- contentSystemId: string;
20
- logger: Payload['logger'];
21
- url: string;
22
- }): Middleware;
23
- export declare function createErrorMiddleware(opts: {
24
- auth: AuthMode;
25
- contentSystemId: string;
26
- logger: Payload['logger'];
27
- url: string;
28
- }): Middleware;
29
- export {};
@@ -1,82 +0,0 @@
1
- import { getValidProjectToken } from '../../auth/project-token.js';
2
- // Module-level cache for dev JWT tokens
3
- const devJwtCache = new Map();
4
- export async function fetchDevJwt(url, contentSystemId) {
5
- const usesSuperUser = !contentSystemId || contentSystemId === 'test-system' || contentSystemId === '*';
6
- const contentSystemIdForJWT = usesSuperUser ? '*' : contentSystemId;
7
- const response = await fetch(`${url}/dev/jwt`, {
8
- body: JSON.stringify({
9
- content_system_id: contentSystemIdForJWT
10
- }),
11
- headers: {
12
- 'Content-Type': 'application/json'
13
- },
14
- method: 'POST'
15
- });
16
- if (!response.ok) {
17
- throw new Error(`Failed to get dev JWT: ${response.status} ${response.statusText}`);
18
- }
19
- const { token } = await response.json();
20
- return token;
21
- }
22
- export function createAuthMiddleware(opts) {
23
- return {
24
- async onRequest ({ request }) {
25
- if (opts.auth.mode === 'apiKey') {
26
- request.headers.set('X-Api-Key', opts.auth.apiKey);
27
- } else if (opts.auth.mode === 'tokenStore') {
28
- const token = await getValidProjectToken({
29
- tenantId: opts.contentSystemId,
30
- tokenStore: opts.auth.tokenStore
31
- });
32
- if (!token) {
33
- throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.');
34
- }
35
- request.headers.set('Authorization', `Bearer ${token}`);
36
- } else {
37
- let token = devJwtCache.get(opts.contentSystemId);
38
- if (!token) {
39
- token = await fetchDevJwt(opts.url, opts.contentSystemId);
40
- devJwtCache.set(opts.contentSystemId, token);
41
- opts.logger.info(`Dev JWT acquired for content system: ${opts.contentSystemId}`);
42
- }
43
- request.headers.set('Authorization', `Bearer ${token}`);
44
- }
45
- return request;
46
- }
47
- };
48
- }
49
- export function createErrorMiddleware(opts) {
50
- return {
51
- async onResponse ({ request, response }) {
52
- if (!response.ok) {
53
- // Handle 401 retry for dev JWT
54
- if (response.status === 401 && opts.auth.mode === 'devJwt') {
55
- const retryCount = parseInt(request.headers.get('X-Retry-Count') || '0', 10);
56
- if (retryCount < 1) {
57
- opts.logger.info('Dev JWT expired, refreshing...');
58
- devJwtCache.delete(opts.contentSystemId);
59
- const newToken = await fetchDevJwt(opts.url, opts.contentSystemId);
60
- devJwtCache.set(opts.contentSystemId, newToken);
61
- // duplex: 'half' is required for Node.js fetch with streaming body
62
- const newRequest = new Request(request.url, {
63
- body: request.body,
64
- duplex: 'half',
65
- headers: new Headers(request.headers),
66
- method: request.method
67
- });
68
- newRequest.headers.set('X-Retry-Count', '1');
69
- newRequest.headers.set('Authorization', `Bearer ${newToken}`);
70
- return fetch(newRequest);
71
- }
72
- }
73
- const text = await response.clone().text();
74
- opts.logger.error({
75
- msg: `HTTP ${response.status} from ${request.url}`,
76
- response: text
77
- });
78
- }
79
- return response;
80
- }
81
- };
82
- }