@payloadcms/figma 1.0.0-beta.2 → 1.0.0-beta.4

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.
@@ -9,6 +9,7 @@ import { getGlobalSlug } from './temp-utilities/slug.js';
9
9
  import { addFallbackSort } from './temp-utilities/sorting.js';
10
10
  import { unwrapDocument, unwrapFindResponse } from './temp-utilities/unwrapDocument.js';
11
11
  import { getClientVersionHeaders } from './utilities/clientVersionHeaders.js';
12
+ import { getCorrelationHeaders } from './utilities/correlationIds.js';
12
13
  import { dataToContentAPI, resolveVersionContent } from './utilities/data/index.js';
13
14
  import { injectGlobalType } from './utilities/data/injectGlobalType.js';
14
15
  import { validateRelationshipIds } from './utilities/data/validateRelationships.js';
@@ -39,6 +40,7 @@ async function syncCollections() {
39
40
  let existingIds;
40
41
  try {
41
42
  const { data: response, error, response: httpResponse } = await this.client.GET('/api/v0/content_systems/{contentSystemId}/collections', {
43
+ headers: getCorrelationHeaders(),
42
44
  params: {
43
45
  path: {
44
46
  contentSystemId: this.contentSystemId
@@ -104,6 +106,7 @@ async function createCollection(collectionId) {
104
106
  body: {
105
107
  id: collectionId
106
108
  },
109
+ headers: getCorrelationHeaders(),
107
110
  params: {
108
111
  path: {
109
112
  contentSystemId: this.contentSystemId
@@ -121,7 +124,7 @@ async function createCollection(collectionId) {
121
124
  }
122
125
  }
123
126
  }
124
- async function findMany({ collection, joins, limit, locale: localeArg, page, pagination: _pagination, sort, where }) {
127
+ async function findMany({ collection, joins, limit, locale: localeArg, page, pagination: _pagination, req, sort, where }) {
125
128
  const locale = addFallbackLocale(localeArg, this.payload);
126
129
  const localeNormalizedWhere = normalizeLocaleInWhere(where, this.payload, collection, locale);
127
130
  const joinClause = convertPayloadJoinsToContentAPI(this.payload, collection, joins);
@@ -136,7 +139,8 @@ async function findMany({ collection, joins, limit, locale: localeArg, page, pag
136
139
  schema: this.documentSchema(),
137
140
  sort: addFallbackSort(sort, this.payload, collection),
138
141
  where: convertPayloadWhereToContentAPI(localeNormalizedWhere, this.payload, collection, false)
139
- }
142
+ },
143
+ headers: getCorrelationHeaders(req)
140
144
  });
141
145
  if (error) {
142
146
  throw createDocumentContentAPIError(this, 'findMany', error, httpResponse.status, collection);
@@ -160,6 +164,7 @@ async function find(args) {
160
164
  locale: args.locale,
161
165
  page: args.page ?? 1,
162
166
  pagination: args.pagination,
167
+ req: args.req,
163
168
  sort: args.sort || collectionConfig?.defaultSort,
164
169
  where: args.where
165
170
  });
@@ -181,7 +186,8 @@ async function findVersions(args) {
181
186
  schema: this.documentSchema(),
182
187
  sort: sortWithFallback,
183
188
  where: whereClause
184
- }
189
+ },
190
+ headers: getCorrelationHeaders(args.req)
185
191
  });
186
192
  if (error) {
187
193
  throw createDocumentContentAPIError(this, 'findVersions', error, httpResponse.status, args.collection);
@@ -198,6 +204,7 @@ async function queryDrafts(args) {
198
204
  locale: args.locale,
199
205
  page: args.page,
200
206
  pagination: args.pagination,
207
+ req: args.req,
201
208
  sort: args.sort,
202
209
  where: {
203
210
  ...args.where,
@@ -240,7 +247,8 @@ async function createVersion(args) {
240
247
  updatedAt: args.updatedAt,
241
248
  version: versionContent
242
249
  }
243
- }
250
+ },
251
+ headers: getCorrelationHeaders(args.req)
244
252
  });
245
253
  if (error) {
246
254
  throw createDocumentContentAPIError(this, 'createVersion', error, httpResponse.status, args.collectionSlug);
@@ -283,7 +291,8 @@ async function updateVersion(args) {
283
291
  version: versionContent
284
292
  },
285
293
  where: convertPayloadWhereToContentAPI(where, this.payload, args.collection, true)
286
- }
294
+ },
295
+ headers: getCorrelationHeaders(args.req)
287
296
  });
288
297
  if (error) {
289
298
  throw createDocumentContentAPIError(this, 'updateVersion', error, httpResponse.status, args.collection);
@@ -318,7 +327,8 @@ async function deleteVersions(args) {
318
327
  locale,
319
328
  schema: this.documentSchema(),
320
329
  where: convertPayloadWhereToContentAPI(args.where, this.payload, collection, true)
321
- }
330
+ },
331
+ headers: getCorrelationHeaders(args.req)
322
332
  });
323
333
  if (error) {
324
334
  throw createDocumentContentAPIError(this, 'deleteVersions', error, httpResponse.status, collection);
@@ -331,6 +341,7 @@ async function findOne(args) {
331
341
  limit: 1,
332
342
  locale: args.locale,
333
343
  pagination: false,
344
+ req: args.req,
334
345
  where: args.where
335
346
  });
336
347
  return docs[0] ?? null;
@@ -348,7 +359,8 @@ async function findDistinct(args) {
348
359
  schema: this.documentSchema(),
349
360
  sort: addFallbackSort(args.sort, this.payload, args.collection),
350
361
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
351
- }
362
+ },
363
+ headers: getCorrelationHeaders(args.req)
352
364
  });
353
365
  if (error) {
354
366
  throw createDocumentContentAPIError(this, 'findDistinct', error, httpResponse.status, args.collection);
@@ -381,7 +393,8 @@ async function updateMany(args) {
381
393
  schema: this.documentSchema(),
382
394
  sort: addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection),
383
395
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
384
- }
396
+ },
397
+ headers: getCorrelationHeaders(args.req)
385
398
  });
386
399
  if (error) {
387
400
  throw createDocumentContentAPIError(this, 'updateMany', error, httpResponse.status, args.collection);
@@ -421,7 +434,8 @@ async function updateOne(args) {
421
434
  locale,
422
435
  schema: this.documentSchema(),
423
436
  where: convertPayloadWhereToContentAPI(where, this.payload, args.collection, false)
424
- }
437
+ },
438
+ headers: getCorrelationHeaders(args.req)
425
439
  });
426
440
  if (error) {
427
441
  throw createDocumentContentAPIError(this, 'updateOne', error, httpResponse.status, args.collection);
@@ -453,7 +467,8 @@ async function deleteMany(args) {
453
467
  locale,
454
468
  schema: this.documentSchema(),
455
469
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
456
- }
470
+ },
471
+ headers: getCorrelationHeaders(args.req)
457
472
  });
458
473
  if (error) {
459
474
  throw createDocumentContentAPIError(this, 'deleteMany', error, httpResponse.status, args.collection);
@@ -469,7 +484,8 @@ async function deleteOne(args) {
469
484
  locale,
470
485
  schema: this.documentSchema(),
471
486
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
472
- }
487
+ },
488
+ headers: getCorrelationHeaders(args.req)
473
489
  });
474
490
  if (error) {
475
491
  throw createDocumentContentAPIError(this, 'deleteOne', error, httpResponse.status, args.collection);
@@ -523,7 +539,8 @@ async function create(args) {
523
539
  environmentName: this.environmentName,
524
540
  locale,
525
541
  schema: this.documentSchema()
526
- }
542
+ },
543
+ headers: getCorrelationHeaders(args.req)
527
544
  });
528
545
  if (error) {
529
546
  redirectInitialAutosaveCreate({
@@ -551,7 +568,8 @@ async function clearDatabase() {
551
568
  const response = await fetch(getClearDatabaseUrl(this.url, process.env.FIGMA_CONTENT_API_CUTOVER_STATE), {
552
569
  headers: {
553
570
  'Content-Type': 'application/json',
554
- ...this.clientVersionHeaders
571
+ ...this.clientVersionHeaders,
572
+ ...getCorrelationHeaders()
555
573
  },
556
574
  method: 'POST'
557
575
  });
@@ -618,7 +636,8 @@ async function count(args) {
618
636
  locale,
619
637
  schema: this.documentSchema(),
620
638
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
621
- }
639
+ },
640
+ headers: getCorrelationHeaders(args.req)
622
641
  });
623
642
  if (error) {
624
643
  throw createDocumentContentAPIError(this, 'count', error, httpResponse.status, args.collection);
@@ -639,7 +658,8 @@ async function countVersions(args) {
639
658
  locale,
640
659
  schema: this.documentSchema(),
641
660
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, true)
642
- }
661
+ },
662
+ headers: getCorrelationHeaders(args.req)
643
663
  });
644
664
  if (error) {
645
665
  throw createDocumentContentAPIError(this, 'countVersions', error, httpResponse.status, args.collection);
@@ -696,7 +716,8 @@ async function upsert(args) {
696
716
  locale,
697
717
  schema: this.documentSchema(),
698
718
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
699
- }
719
+ },
720
+ headers: getCorrelationHeaders(args.req)
700
721
  });
701
722
  if (error) {
702
723
  throw createDocumentContentAPIError(this, 'upsert', error, httpResponse.status, args.collection);
@@ -756,7 +777,8 @@ async function updateJobs(args) {
756
777
  schema: this.documentSchema(),
757
778
  sort: sortClause,
758
779
  where: whereQuery
759
- }
780
+ },
781
+ headers: getCorrelationHeaders(args.req)
760
782
  });
761
783
  if (error) {
762
784
  throw createDocumentContentAPIError(this, 'updateJobs', error, httpResponse.status, collection);
@@ -788,6 +810,7 @@ async function createGlobal(args) {
788
810
  ...args.data,
789
811
  id: args.slug
790
812
  },
813
+ req: args.req,
791
814
  where: {
792
815
  id: {
793
816
  equals: args.slug
@@ -800,6 +823,7 @@ async function findGlobal(args) {
800
823
  const doc = await this.findOne({
801
824
  collection: getGlobalSlug(args.slug),
802
825
  locale: args.locale,
826
+ req: args.req,
803
827
  where: args.where ?? {}
804
828
  });
805
829
  return injectGlobalType(doc, args.slug);
@@ -808,6 +832,7 @@ async function updateGlobal(args) {
808
832
  const doc = await this.upsert({
809
833
  collection: getGlobalSlug(args.slug),
810
834
  data: args.data,
835
+ req: args.req,
811
836
  where: {
812
837
  id: {
813
838
  equals: args.slug
@@ -824,6 +849,7 @@ function findGlobalVersions(args) {
824
849
  locale: args.locale,
825
850
  page: args.page,
826
851
  pagination: args.pagination,
852
+ req: args.req,
827
853
  sort: args.sort,
828
854
  where: args.where
829
855
  });
@@ -837,6 +863,7 @@ function createGlobalVersion(args) {
837
863
  createdAt: args.createdAt,
838
864
  parent: args.globalSlug,
839
865
  publishedLocale: args.publishedLocale,
866
+ req: args.req,
840
867
  updatedAt: args.updatedAt,
841
868
  versionData: args.versionData
842
869
  });
@@ -848,6 +875,7 @@ function updateGlobalVersion(args) {
848
875
  id: args.id,
849
876
  collection: getGlobalSlug(args.global),
850
877
  locale: args.locale,
878
+ req: args.req,
851
879
  versionData: args.versionData
852
880
  });
853
881
  }
@@ -855,6 +883,7 @@ function updateGlobalVersion(args) {
855
883
  return this.updateVersion({
856
884
  collection: getGlobalSlug(args.global),
857
885
  locale: args.locale,
886
+ req: args.req,
858
887
  versionData: args.versionData,
859
888
  where: args.where
860
889
  });
@@ -863,6 +892,7 @@ function countGlobalVersions(args) {
863
892
  return this.countVersions({
864
893
  collection: getGlobalSlug(args.global),
865
894
  locale: args.locale,
895
+ req: args.req,
866
896
  where: args.where
867
897
  });
868
898
  }
@@ -0,0 +1,18 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ export declare const FIGMA_ROOT_REQ_ID_HEADER = "Figma-Root-Req-ID";
3
+ export declare const FIGMA_PARENT_REQ_ID_HEADER = "Figma-Parent-Req-ID";
4
+ export type CorrelationIds = {
5
+ /** The current operation (this Payload app). */
6
+ leafId: string;
7
+ /** The operation that called this Payload app, or null when there is none. */
8
+ parentId: null | string;
9
+ /** The operation that started the call tree. */
10
+ rootId: string;
11
+ };
12
+ /**
13
+ * Correlation IDs for a Payload request, stable for the lifetime of that request object.
14
+ * Calls without a request (e.g. collection sync on connect) each start their own call tree.
15
+ */
16
+ export declare function getCorrelationIds(req?: Partial<PayloadRequest>): CorrelationIds;
17
+ /** Headers that identify this Payload app as the parent of an outgoing Content API request. */
18
+ export declare function getCorrelationHeaders(req?: Partial<PayloadRequest>): Record<string, string>;
@@ -0,0 +1,42 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export const FIGMA_ROOT_REQ_ID_HEADER = 'Figma-Root-Req-ID';
3
+ export const FIGMA_PARENT_REQ_ID_HEADER = 'Figma-Parent-Req-ID';
4
+ const correlationIdsByRequest = new WeakMap();
5
+ function buildCorrelationIds(headers) {
6
+ const leafId = randomUUID();
7
+ const rootId = headers?.get(FIGMA_ROOT_REQ_ID_HEADER);
8
+ if (!rootId) {
9
+ // Without a root, a parent cannot be placed in a call tree, so this request starts a new one.
10
+ return {
11
+ leafId,
12
+ parentId: null,
13
+ rootId: leafId
14
+ };
15
+ }
16
+ return {
17
+ leafId,
18
+ parentId: headers?.get(FIGMA_PARENT_REQ_ID_HEADER) || null,
19
+ rootId
20
+ };
21
+ }
22
+ /**
23
+ * Correlation IDs for a Payload request, stable for the lifetime of that request object.
24
+ * Calls without a request (e.g. collection sync on connect) each start their own call tree.
25
+ */ export function getCorrelationIds(req) {
26
+ if (!req) {
27
+ return buildCorrelationIds(undefined);
28
+ }
29
+ let ids = correlationIdsByRequest.get(req);
30
+ if (!ids) {
31
+ ids = buildCorrelationIds(req.headers);
32
+ correlationIdsByRequest.set(req, ids);
33
+ }
34
+ return ids;
35
+ }
36
+ /** Headers that identify this Payload app as the parent of an outgoing Content API request. */ export function getCorrelationHeaders(req) {
37
+ const { leafId, rootId } = getCorrelationIds(req);
38
+ return {
39
+ [FIGMA_PARENT_REQ_ID_HEADER]: leafId,
40
+ [FIGMA_ROOT_REQ_ID_HEADER]: rootId
41
+ };
42
+ }
@@ -3,6 +3,7 @@ import { generateCookie, parseCookies } from 'payload';
3
3
  import { clearSessionCookies } from '../utilities/clearSessionCookies.js';
4
4
  import { createCookieOptions } from '../utilities/createCookieOptions.js';
5
5
  import { createDebugLogger } from '../utilities/createDebugLogger.js';
6
+ import { createTokenCookie } from '../utilities/createTokenCookie.js';
6
7
  import { getCookieExpiration } from '../utilities/getCookieExpiration.js';
7
8
  import { getTokenExp } from '../utilities/getTokenExp.js';
8
9
  import { mergeHeaders } from '../utilities/mergeHeaders.js';
@@ -70,10 +71,9 @@ export const getRefreshHook = ({ pluginOptions, strategy })=>async ({ args, user
70
71
  return undefined;
71
72
  }
72
73
  const result = await refreshTokens({
73
- headers: args.req.headers,
74
+ debug: strategy.debug,
74
75
  payload: args.req.payload,
75
- refreshToken,
76
- strategy
76
+ refreshToken
77
77
  });
78
78
  if (result.status !== 'success') {
79
79
  if (result.status === 'rejected') {
@@ -84,7 +84,12 @@ export const getRefreshHook = ({ pluginOptions, strategy })=>async ({ args, user
84
84
  }
85
85
  return undefined;
86
86
  }
87
- mergeHeaders(result.headers, args.req.responseHeaders);
87
+ mergeHeaders(createTokenCookie({
88
+ expiresAt: result.expiresAt,
89
+ headers: args.req.headers,
90
+ strategy,
91
+ token: result.token
92
+ }), args.req.responseHeaders);
88
93
  if (result.decodedOauthToken.exp) {
89
94
  return {
90
95
  exp: result.decodedOauthToken.exp,
@@ -4,6 +4,7 @@ import { JWTValidationError, validatePayloadAdminToken } from '../../auth/jwt-va
4
4
  import { getInfraEnvironment } from '../../constants.js';
5
5
  import { clearSessionCookies } from '../utilities/clearSessionCookies.js';
6
6
  import { createDebugLogger } from '../utilities/createDebugLogger.js';
7
+ import { createTokenCookie } from '../utilities/createTokenCookie.js';
7
8
  import { getTokenExp } from '../utilities/getTokenExp.js';
8
9
  import { mergeHeaders } from '../utilities/mergeHeaders.js';
9
10
  import { refreshTokens } from '../utilities/refreshTokens.js';
@@ -76,10 +77,9 @@ export class Strategy {
76
77
  msg: 'No access token found, but refresh token exists. Attempting to refresh...'
77
78
  });
78
79
  const refreshed = await refreshTokens({
79
- headers,
80
+ debug: this.debug,
80
81
  payload,
81
- refreshToken,
82
- strategy: this
82
+ refreshToken
83
83
  });
84
84
  if (refreshed.status === 'success') {
85
85
  const tokenExpiration = refreshed.decodedOauthToken.exp;
@@ -101,11 +101,17 @@ export class Strategy {
101
101
  // During RSC navigation, canSetHeaders=false because response streaming
102
102
  // has already started and cookies cannot be modified.
103
103
  if (canSetHeaders) {
104
+ const responseHeaders = createTokenCookie({
105
+ expiresAt: refreshed.expiresAt,
106
+ headers,
107
+ strategy: this,
108
+ token: refreshed.token
109
+ });
104
110
  if (verifyResult.responseHeaders) {
105
- mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
111
+ mergeHeaders(verifyResult.responseHeaders, responseHeaders);
106
112
  }
107
113
  return {
108
- responseHeaders: refreshed.headers,
114
+ responseHeaders,
109
115
  user: verifyResult.user
110
116
  };
111
117
  }
@@ -177,10 +183,9 @@ export class Strategy {
177
183
  // but only update cookies when canSetHeaders=true.
178
184
  if (oauthTokenVerifyResult instanceof JWTValidationError && oauthTokenVerifyResult.code === 'EXPIRED' && refreshToken && !this.collectionOptions.usePayloadJWT) {
179
185
  const refreshed = await refreshTokens({
180
- headers,
186
+ debug: this.debug,
181
187
  payload,
182
- refreshToken,
183
- strategy: this
188
+ refreshToken
184
189
  });
185
190
  debugLogger.info({
186
191
  msg: 'Token expired. Refreshing...'
@@ -202,11 +207,17 @@ export class Strategy {
202
207
  verifyResult
203
208
  });
204
209
  if (canSetHeaders) {
210
+ const responseHeaders = createTokenCookie({
211
+ expiresAt: refreshed.expiresAt,
212
+ headers,
213
+ strategy: this,
214
+ token: refreshed.token
215
+ });
205
216
  if (verifyResult.responseHeaders) {
206
- mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
217
+ mergeHeaders(verifyResult.responseHeaders, responseHeaders);
207
218
  }
208
219
  return {
209
- responseHeaders: refreshed.headers,
220
+ responseHeaders,
210
221
  user: verifyResult.user
211
222
  };
212
223
  }
@@ -333,10 +344,19 @@ export class Strategy {
333
344
  return verified;
334
345
  }
335
346
  } catch (err) {
336
- payload.logger.error({
337
- err,
338
- msg: 'Error verifying jwt token'
339
- });
347
+ // Not a JWT at all, like the MCP endpoint's sealed access tokens, which plugin-mcp
348
+ // authenticates after this strategy declines them. The client's mistake, not the server's.
349
+ if (err instanceof JWTValidationError && err.code === 'MISSING_KID') {
350
+ createDebugLogger(payload, this.debug).info({
351
+ err,
352
+ msg: 'Token is not a JWT'
353
+ });
354
+ } else {
355
+ payload.logger.error({
356
+ err,
357
+ msg: 'Error verifying jwt token'
358
+ });
359
+ }
340
360
  if (err instanceof Error) {
341
361
  return err;
342
362
  }
@@ -0,0 +1,11 @@
1
+ import type { Strategy } from '../strategy/index.js';
2
+ interface Args {
3
+ expiresAt: number;
4
+ /** The request's headers, which decide the cookie's options */
5
+ headers: Headers;
6
+ strategy: Strategy;
7
+ token: string;
8
+ }
9
+ /** Response headers that keep a Payload Admin token from `refreshTokens` in the login's cookie */
10
+ export declare const createTokenCookie: ({ expiresAt, headers: requestHeaders, strategy, token, }: Args) => Headers;
11
+ export {};
@@ -0,0 +1,21 @@
1
+ import { generateCookie } from 'payload';
2
+ import { createCookieOptions } from './createCookieOptions.js';
3
+ import { getCookieExpiration } from './getCookieExpiration.js';
4
+ import { withPartitionedCookie } from './withPartitionedCookie.js';
5
+ /** Response headers that keep a Payload Admin token from `refreshTokens` in the login's cookie */ export const createTokenCookie = ({ expiresAt, headers: requestHeaders, strategy, token })=>{
6
+ const cookieOptions = createCookieOptions({
7
+ collection: strategy.collection,
8
+ headers: requestHeaders,
9
+ pluginOptions: strategy.pluginOptions
10
+ });
11
+ const tokenCookie = generateCookie({
12
+ ...cookieOptions,
13
+ name: strategy.cookieName,
14
+ expires: getCookieExpiration(new Date(expiresAt)),
15
+ returnCookieAsObject: false,
16
+ value: token
17
+ });
18
+ const headers = new Headers();
19
+ headers.append('Set-Cookie', withPartitionedCookie(tokenCookie));
20
+ return headers;
21
+ };
@@ -1,15 +1,13 @@
1
1
  import type jwt from 'jsonwebtoken';
2
2
  import type { Payload } from 'payload';
3
- import type { Strategy } from '../strategy/index.js';
4
3
  interface Args {
5
- headers: Headers;
4
+ debug?: boolean;
6
5
  payload: Payload;
7
6
  refreshToken: string;
8
- strategy: Strategy;
9
7
  }
10
8
  export type RefreshResult = {
11
9
  decodedOauthToken: jwt.JwtPayload;
12
- headers: Headers;
10
+ expiresAt: number;
13
11
  status: 'success';
14
12
  token: string;
15
13
  } | {
@@ -17,5 +15,9 @@ export type RefreshResult = {
17
15
  } | {
18
16
  status: 'temporary_failure';
19
17
  };
20
- export declare const refreshTokens: ({ headers: requestHeaders, payload, refreshToken, strategy, }: Args) => Promise<RefreshResult>;
18
+ /**
19
+ * Gets a new Payload Admin token from the login's refresh token. The admin panel keeps the
20
+ * result in a cookie (`createTokenCookie`), and MCP clients get it as their access token.
21
+ */
22
+ export declare const refreshTokens: ({ debug, payload, refreshToken, }: Args) => Promise<RefreshResult>;
21
23
  export {};
@@ -1,18 +1,16 @@
1
- import { generateCookie } from 'payload';
2
1
  import { FigmaApiError, getPayloadAdminToken } from '../../api/figma-api.js';
3
2
  import { validatePayloadAdminToken } from '../../auth/jwt-validator.js';
4
3
  import { getInfraEnvironment } from '../../constants.js';
5
- import { createCookieOptions } from './createCookieOptions.js';
6
4
  import { createDebugLogger } from './createDebugLogger.js';
7
- import { getCookieExpiration } from './getCookieExpiration.js';
8
- import { withPartitionedCookie } from './withPartitionedCookie.js';
9
- export const refreshTokens = async ({ headers: requestHeaders, payload, refreshToken, strategy })=>{
10
- const debugLogger = createDebugLogger(payload, strategy.debug);
5
+ /**
6
+ * Gets a new Payload Admin token from the login's refresh token. The admin panel keeps the
7
+ * result in a cookie (`createTokenCookie`), and MCP clients get it as their access token.
8
+ */ export const refreshTokens = async ({ debug, payload, refreshToken })=>{
9
+ const debugLogger = createDebugLogger(payload, debug);
11
10
  debugLogger.info({
12
11
  msg: 'Refreshing tokens'
13
12
  });
14
- const headers = new Headers();
15
- // The refresh cookie holds an OAuth access token. Use it to mint a new
13
+ // The refresh token is an OAuth access token. Use it to mint a new
16
14
  // session JWT; this does not rotate an OAuth refresh token.
17
15
  try {
18
16
  // Get another Payload Admin token.
@@ -45,23 +43,9 @@ export const refreshTokens = async ({ headers: requestHeaders, payload, refreshT
45
43
  environment: getInfraEnvironment(),
46
44
  token
47
45
  });
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
46
  return {
63
47
  decodedOauthToken,
64
- headers,
48
+ expiresAt,
65
49
  status: 'success',
66
50
  token
67
51
  };
@@ -383,6 +383,8 @@ export async function buildFigmaConfig(config) {
383
383
  bootstrapFetched
384
384
  }) : '';
385
385
  const isProduction = process.env.NODE_ENV === 'production';
386
+ // The Figma login's cookie names, which local dev keeps apart per app
387
+ const devCookieNames = isProduction ? undefined : getDevCookieNames(contentSystemId, config.cookiePrefix);
386
388
  // The deployed Lambda runs all queued jobs; locally there is no runner, so the db adapter logs
387
389
  // a heads-up whenever a job is queued. Deployed environments set DISABLE_LOCAL_JOB_QUEUE_NOTIFICATIONS=true
388
390
  // (injected by the control plane); end-users can also set it locally to silence the notice.
@@ -562,12 +564,15 @@ export async function buildFigmaConfig(config) {
562
564
  usernameField: 'email'
563
565
  }
564
566
  ],
565
- ...isProduction ? {} : getDevCookieNames(contentSystemId, config.cookiePrefix),
567
+ ...devCookieNames,
566
568
  debug: !!process.env.DEBUG,
567
569
  disabled: false
568
570
  }),
569
571
  scheduleExtractPlugin(),
570
- createMCPOAuthPlugin(),
572
+ createMCPOAuthPlugin({
573
+ // Where the Figma login above keeps its refresh token
574
+ refreshTokenCookie: `${devCookieNames?.cookieName ?? 'payload-oauth-token'}-refresh`
575
+ }),
571
576
  // Not folded into createStoragePlugin, which is skipped when
572
577
  // figma.storage is false and would break remote uploads for those apps.
573
578
  createSandboxUploadFetchPlugin({
@@ -1,10 +1,21 @@
1
1
  /**
2
- * Turns off `@payloadcms/plugin-mcp`'s OAuth login in apps that use plugin-mcp, unless the app
3
- * sets plugin-mcp's `oauth` option itself. Newer versions of plugin-mcp turn that login on by
4
- * default, but its default tokens need Payload's password login, which Figma apps turn off, so
5
- * MCP clients would be asked to log in and then fail. MCP clients keep using API keys.
2
+ * Lets MCP clients, like Codex or Figma Agent, log in to the app with Figma. It turns on
3
+ * `@payloadcms/plugin-mcp`'s built-in OAuth server and fills in the part that is specific to
4
+ * Figma login, so apps don't configure anything. It sets plugin-mcp's `oauth` option before
5
+ * plugin-mcp runs, unless the app already set one.
6
6
  *
7
- * It only sets an option on plugin-mcp, so apps without plugin-mcp don't get it. Versions of
8
- * plugin-mcp without the option ignore it.
7
+ * The admin panel's Figma login keeps two cookies: a Payload Admin token, which logs the user
8
+ * in and lasts a few minutes, and the user's Figma access token. When the Payload Admin token
9
+ * expires, the admin panel uses the Figma access token as a refresh token to get a new one
10
+ * (`refreshTokens`).
11
+ *
12
+ * With plugin-mcp, an MCP client sends the user to the app's Allow page in the browser, where
13
+ * they log in to the admin panel if needed and click Allow. plugin-mcp then needs tokens for
14
+ * the client, but doesn't know about the admin login's cookies. `issueToken` and
15
+ * `refreshToken` fill that in: they give the client its own Payload Admin token, sealed for MCP,
16
+ * and the same refresh token, so it can refresh the way the admin panel does.
9
17
  */
10
- export declare const createMCPOAuthPlugin: () => import("payload").Plugin;
18
+ export declare const createMCPOAuthPlugin: (options: {
19
+ /** The cookie the admin login keeps its refresh token, the user's Figma access token, in */
20
+ refreshTokenCookie: string;
21
+ }) => import("payload").Plugin;
@@ -1,22 +1,135 @@
1
- import { definePlugin } from 'payload';
1
+ // Types plugin-mcp's options in `plugins`, so its hooks below are checked against its config
2
+ import { APIError, definePlugin, executeAuthStrategies, parseCookies } from 'payload';
3
+ import { formatAdminURL, stripTrailingSlash } from 'payload/shared';
4
+ import { refreshTokens } from '../oauth/utilities/refreshTokens.js';
5
+ const ACCESS_TOKEN_TYPE = 'figma-mcp-access';
2
6
  /**
3
- * Turns off `@payloadcms/plugin-mcp`'s OAuth login in apps that use plugin-mcp, unless the app
4
- * sets plugin-mcp's `oauth` option itself. Newer versions of plugin-mcp turn that login on by
5
- * default, but its default tokens need Payload's password login, which Figma apps turn off, so
6
- * MCP clients would be asked to log in and then fail. MCP clients keep using API keys.
7
+ * Seals the Payload Admin token an MCP client gets, like plugin-mcp's default `issueToken`, so
8
+ * it only works at the MCP endpoint, where `authenticate` unseals it. Raw, it would work as the
9
+ * user's admin panel login on every route.
10
+ */ const sealAccessToken = (req, token)=>req.payload.encrypt(JSON.stringify({
11
+ type: ACCESS_TOKEN_TYPE,
12
+ token
13
+ }));
14
+ const unsealAccessToken = (req, value)=>{
15
+ if (!value.startsWith('v1:')) {
16
+ return undefined;
17
+ }
18
+ try {
19
+ const data = JSON.parse(req.payload.decrypt(value));
20
+ return data.type === ACCESS_TOKEN_TYPE && typeof data.token === 'string' ? data.token : undefined;
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ };
25
+ /**
26
+ * The tokens plugin-mcp gives an MCP client, from a `refreshTokens` result: the new Payload
27
+ * Admin token, sealed, and the same refresh token, which plugin-mcp seals so clients can't
28
+ * read it. Returns `null`, which signs the client out, when Figma refuses, e.g. because the
29
+ * user lost access to the app.
30
+ */ const toTokens = (req, refreshed, refreshToken)=>{
31
+ if (refreshed.status === 'rejected') {
32
+ return null;
33
+ }
34
+ // Other errors, like Figma being down, shouldn't sign MCP clients out
35
+ if (refreshed.status === 'temporary_failure') {
36
+ throw new APIError('Could not get a Payload token from Figma. Try again.', 503);
37
+ }
38
+ return {
39
+ accessToken: sealAccessToken(req, refreshed.token),
40
+ expiresIn: Math.floor((refreshed.expiresAt - Date.now()) / 1000),
41
+ refreshToken
42
+ };
43
+ };
44
+ /**
45
+ * The MCP endpoint's public URL. A deployed app's request URL is the server's own address, like
46
+ * `https://0.0.0.0:3000`, but Figma's sites worker sets `x-forwarded-host` to the host the
47
+ * client used, which can be the `figma.site` domain or a custom one. The path is plugin-mcp's
48
+ * default, which includes Next.js's `basePath`.
49
+ */ const getMCPResource = ({ req })=>{
50
+ const { routes, serverURL } = req.payload.config;
51
+ const requestURL = new URL(serverURL || req.url);
52
+ // With several proxies in a row, the first value is the client's
53
+ const host = serverURL ? undefined : (req.headers.get('x-forwarded-host') ?? req.headers.get('host'))?.split(',')[0].trim();
54
+ const protocol = req.headers.get('x-forwarded-proto')?.split(',')[0].trim() ?? requestURL.protocol.slice(0, -1);
55
+ const origin = host ? `${protocol}://${host}` : requestURL.origin;
56
+ // Without the slash Next.js's `trailingSlash` would add, since plugin-mcp appends to it
57
+ const path = stripTrailingSlash(formatAdminURL({
58
+ apiRoute: routes.api,
59
+ path: '/mcp'
60
+ }));
61
+ return new URL(path, origin).href;
62
+ };
63
+ /**
64
+ * Lets MCP clients, like Codex or Figma Agent, log in to the app with Figma. It turns on
65
+ * `@payloadcms/plugin-mcp`'s built-in OAuth server and fills in the part that is specific to
66
+ * Figma login, so apps don't configure anything. It sets plugin-mcp's `oauth` option before
67
+ * plugin-mcp runs, unless the app already set one.
68
+ *
69
+ * The admin panel's Figma login keeps two cookies: a Payload Admin token, which logs the user
70
+ * in and lasts a few minutes, and the user's Figma access token. When the Payload Admin token
71
+ * expires, the admin panel uses the Figma access token as a refresh token to get a new one
72
+ * (`refreshTokens`).
7
73
  *
8
- * It only sets an option on plugin-mcp, so apps without plugin-mcp don't get it. Versions of
9
- * plugin-mcp without the option ignore it.
74
+ * With plugin-mcp, an MCP client sends the user to the app's Allow page in the browser, where
75
+ * they log in to the admin panel if needed and click Allow. plugin-mcp then needs tokens for
76
+ * the client, but doesn't know about the admin login's cookies. `issueToken` and
77
+ * `refreshToken` fill that in: they give the client its own Payload Admin token, sealed for MCP,
78
+ * and the same refresh token, so it can refresh the way the admin panel does.
10
79
  */ export const createMCPOAuthPlugin = definePlugin({
11
80
  slug: '@payloadcms/figma/mcp-oauth',
12
- // Before @payloadcms/plugin-mcp, which runs at order 10 and reads its options then
81
+ // Before @payloadcms/plugin-mcp, which runs at order 10
13
82
  order: 5,
14
- plugin: ({ config, plugins })=>{
83
+ plugin: ({ config, options: { refreshTokenCookie }, plugins })=>{
15
84
  const mcp = plugins['@payloadcms/plugin-mcp'];
85
+ // plugin-mcp reads its options when it runs. `oauth: false` turns OAuth off.
16
86
  if (mcp && mcp.options?.oauth === undefined) {
17
87
  mcp.options = {
18
88
  ...mcp.options,
19
- oauth: false
89
+ oauth: {
90
+ type: 'builtin',
91
+ authenticate: async ({ req, token })=>{
92
+ const adminToken = unsealAccessToken(req, token);
93
+ if (!adminToken) {
94
+ return null;
95
+ }
96
+ const headers = new Headers({
97
+ Authorization: `Bearer ${adminToken}`,
98
+ DisableAutologin: 'true'
99
+ });
100
+ return (await executeAuthStrategies({
101
+ headers,
102
+ payload: req.payload,
103
+ req
104
+ })).user;
105
+ },
106
+ /**
107
+ * When the user clicks Allow. Reads the refresh token from the browser's cookies.
108
+ * plugin-mcp gives the client fresh tokens from `refreshToken` when it trades its
109
+ * authorization code, but getting a Payload Admin token here already checks that
110
+ * Figma still accepts the user, so they see the error in the browser.
111
+ */ issueToken: async ({ req })=>{
112
+ const refreshToken = parseCookies(req.headers).get(refreshTokenCookie);
113
+ const tokens = refreshToken && toTokens(req, await refreshTokens({
114
+ payload: req.payload,
115
+ refreshToken
116
+ }), refreshToken);
117
+ if (!tokens) {
118
+ throw new APIError('Log in to the admin panel again, then allow the MCP client.', 401);
119
+ }
120
+ return tokens;
121
+ },
122
+ /**
123
+ * When the client trades its authorization code, and when its Payload Admin token
124
+ * expires. There's no browser then, so this uses the refresh token `issueToken`
125
+ * returned. It keeps working until the user's Figma access token expires.
126
+ */ refreshToken: async ({ refreshToken, req })=>toTokens(req, await refreshTokens({
127
+ payload: req.payload,
128
+ refreshToken
129
+ }), refreshToken),
130
+ // plugin-mcp also bases its metadata link and login server's address on it
131
+ resource: getMCPResource
132
+ }
20
133
  };
21
134
  }
22
135
  return config;
@@ -18,9 +18,9 @@ do not ask `@payloadcms/figma` what framework this is, and do not guess. When th
18
18
  evidence conflicts or the shape isn't one Figma Cloud supports, **stop** before
19
19
  touching auth or deploy.
20
20
 
21
- Run the CLI with `npx @payloadcms/figma@alpha <...>` **from the target folder**.
21
+ Run the CLI with `npx @payloadcms/figma@latest <...>` **from the target folder**.
22
22
  If a different invocation is already established in the repo (e.g.
23
- `pnpm start --`), use that instead — but `npx @payloadcms/figma@alpha` is the
23
+ `pnpm start --`), use that instead — but `npx @payloadcms/figma@latest` is the
24
24
  default.
25
25
 
26
26
  If the user's request contains **“Figma staging”** (case-insensitive), append
@@ -149,7 +149,7 @@ The deploy command needs a valid credential and cannot open a browser in a
149
149
  headless/agent context, so authenticate first with the resumable headless flow.
150
150
 
151
151
  ```bash
152
- npx @payloadcms/figma@alpha login --headless --json
152
+ npx @payloadcms/figma@latest login --headless --json
153
153
  ```
154
154
 
155
155
  Parse `status`:
@@ -161,7 +161,7 @@ Parse `status`:
161
161
  `http://localhost:.../callback?...` address the browser lands on). Then:
162
162
 
163
163
  ```bash
164
- npx @payloadcms/figma@alpha login --complete <sessionId> --callback-url '<redirect-url>' --json
164
+ npx @payloadcms/figma@latest login --complete <sessionId> --callback-url '<redirect-url>' --json
165
165
  ```
166
166
 
167
167
  Quote the callback URL in single quotes. Expect `{"status":"authenticated",...}`.
@@ -180,7 +180,7 @@ Run **from the target folder**, non-interactively with `-y`. Always pass
180
180
  explicit `--adapter` / `--output` you verified in Steps 2–3:
181
181
 
182
182
  ```bash
183
- npx @payloadcms/figma@alpha deploy -y --skip-build --adapter <nextjs|nitro|vite> --output <verified-root>
183
+ npx @payloadcms/figma@latest deploy -y --skip-build --adapter <nextjs|nitro|vite> --output <verified-root>
184
184
  ```
185
185
 
186
186
  Add the project-creation flags from Step 4 only for an uninitialized project.
@@ -189,13 +189,13 @@ Examples:
189
189
 
190
190
  ```bash
191
191
  # Next.js app in a monorepo package (already initialized), built to .next
192
- npx @payloadcms/figma@alpha deploy -y --skip-build --adapter nextjs --output .next
192
+ npx @payloadcms/figma@latest deploy -y --skip-build --adapter nextjs --output .next
193
193
 
194
194
  # Vite single-page app, built to dist
195
- npx @payloadcms/figma@alpha deploy -y --skip-build --adapter vite --output dist
195
+ npx @payloadcms/figma@latest deploy -y --skip-build --adapter vite --output dist
196
196
 
197
197
  # Simple static folder (index.html at the folder root), no build
198
- npx @payloadcms/figma@alpha deploy -y --skip-build --adapter vite --output .
198
+ npx @payloadcms/figma@latest deploy -y --skip-build --adapter vite --output .
199
199
  ```
200
200
 
201
201
  ### Deterministic retry — workspace selection
@@ -99,7 +99,7 @@ The deploy command is always explicit — the agent supplies the verified adapte
99
99
  and output root and skips the build (it already ran, or the folder is static):
100
100
 
101
101
  ```bash
102
- npx @payloadcms/figma@alpha deploy -y --skip-build --adapter <nextjs|nitro|vite> --output <root>
102
+ npx @payloadcms/figma@latest deploy -y --skip-build --adapter <nextjs|nitro|vite> --output <root>
103
103
  ```
104
104
 
105
105
  | Flag | Purpose |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/figma",
3
- "version": "1.0.0-beta.2",
3
+ "version": "1.0.0-beta.4",
4
4
  "license": "SEE LICENSE IN LICENSE.md",
5
5
  "type": "module",
6
6
  "exports": {
@@ -38,8 +38,8 @@
38
38
  ],
39
39
  "dependencies": {
40
40
  "@clack/prompts": "^0.11.0",
41
- "@cloudflare/workers-types": "5.20260716.1",
42
- "@figma/rest-api-spec": "^0.34.0",
41
+ "@cloudflare/workers-types": "^5.20261108.1",
42
+ "@figma/rest-api-spec": "^0.45.0",
43
43
  "@sindresorhus/slugify": "^3.0.0",
44
44
  "archiver": "7.0.1",
45
45
  "arg": "^5.0.2",
@@ -48,7 +48,7 @@
48
48
  "dotenv": "^16.4.5",
49
49
  "env-paths": "^3.0.0",
50
50
  "figures": "^6.1.0",
51
- "jose": "6.0.12",
51
+ "jose": "^6.2.1",
52
52
  "jsonwebtoken": "9.0.3",
53
53
  "open": "^10.2.0",
54
54
  "openapi-fetch": "0.15.0",
@@ -58,16 +58,18 @@
58
58
  "skills": "1.4.4",
59
59
  "tar": "^7.5.21",
60
60
  "terminal-link": "^5.0.0",
61
- "ts-morph": "^21.0.1"
61
+ "ts-morph": "^27.0.0"
62
62
  },
63
63
  "devDependencies": {
64
+ "@payloadcms/db-sqlite": "4.0.0-beta.9",
64
65
  "@payloadcms/eslint-config": "3.28.0",
65
66
  "@payloadcms/eslint-plugin": "3.28.0",
66
- "@payloadcms/next": "4.0.0-beta.8",
67
- "@payloadcms/plugin-cloud-storage": "4.0.0-beta.8",
68
- "@payloadcms/richtext-lexical": "4.0.0-beta.8",
69
- "@payloadcms/translations": "4.0.0-beta.8",
70
- "@payloadcms/ui": "4.0.0-beta.8",
67
+ "@payloadcms/next": "4.0.0-beta.9",
68
+ "@payloadcms/plugin-cloud-storage": "4.0.0-beta.9",
69
+ "@payloadcms/plugin-mcp": "4.0.0-beta.9",
70
+ "@payloadcms/richtext-lexical": "4.0.0-beta.9",
71
+ "@payloadcms/translations": "4.0.0-beta.9",
72
+ "@payloadcms/ui": "4.0.0-beta.9",
71
73
  "@swc/cli": "0.7.7",
72
74
  "@types/archiver": "7.0.0",
73
75
  "@types/cross-spawn": "6.0.6",
@@ -77,7 +79,7 @@
77
79
  "eslint": "9.22.0",
78
80
  "next": "^16.4.2",
79
81
  "openapi-typescript": "^7.13.0",
80
- "payload": "4.0.0-beta.8",
82
+ "payload": "4.0.0-beta.9",
81
83
  "react": "^19.3.1",
82
84
  "react-dom": "^19.3.1",
83
85
  "tsx": "4.20.6",
@@ -85,11 +87,11 @@
85
87
  "vitest": "4.0.15"
86
88
  },
87
89
  "peerDependencies": {
88
- "@payloadcms/plugin-cloud-storage": ">=4.0.0-beta.8 <4.0.0-internal",
89
- "@payloadcms/richtext-lexical": ">=4.0.0-beta.8 <4.0.0-internal",
90
- "@payloadcms/translations": ">=4.0.0-beta.8 <4.0.0-internal",
91
- "@payloadcms/ui": ">=4.0.0-beta.8 <4.0.0-internal",
92
- "payload": ">=4.0.0-beta.8 <4.0.0-internal",
90
+ "@payloadcms/plugin-cloud-storage": ">=4.0.0-beta.9 <4.0.0-internal",
91
+ "@payloadcms/richtext-lexical": ">=4.0.0-beta.9 <4.0.0-internal",
92
+ "@payloadcms/translations": ">=4.0.0-beta.9 <4.0.0-internal",
93
+ "@payloadcms/ui": ">=4.0.0-beta.9 <4.0.0-internal",
94
+ "payload": ">=4.0.0-beta.9 <4.0.0-internal",
93
95
  "react": "^19.3.1"
94
96
  },
95
97
  "peerDependenciesMeta": {