@payloadcms/figma 1.0.0-beta.1 → 1.0.0-beta.3

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 (47) 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/generated/content-api-types.d.ts +247 -0
  7. package/dist/db-content-api/index.js +87 -20
  8. package/dist/db-content-api/utilities/correlationIds.d.ts +18 -0
  9. package/dist/db-content-api/utilities/correlationIds.js +42 -0
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.js +1 -0
  12. package/dist/oauth/defaults.js +2 -2
  13. package/dist/oauth/hooks/me.d.ts +4 -3
  14. package/dist/oauth/hooks/me.js +6 -52
  15. package/dist/oauth/hooks/refresh.js +9 -1
  16. package/dist/oauth/index.js +1 -1
  17. package/dist/oauth/strategy/index.d.ts +3 -0
  18. package/dist/oauth/strategy/index.js +49 -3
  19. package/dist/oauth/utilities/clearCookie.d.ts +1 -0
  20. package/dist/oauth/utilities/clearCookie.js +13 -9
  21. package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
  22. package/dist/oauth/utilities/clearSessionCookies.js +17 -0
  23. package/dist/oauth/utilities/getAuthorizeURL.js +1 -2
  24. package/dist/oauth/utilities/mergeHeaders.js +11 -23
  25. package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
  26. package/dist/oauth/utilities/refreshTokens.js +45 -34
  27. package/dist/plugin/build-config.js +10 -7
  28. package/dist/plugin/dev-cookie-names.d.ts +4 -1
  29. package/dist/plugin/dev-cookie-names.js +6 -3
  30. package/dist/plugin/environment-error.d.ts +4 -0
  31. package/dist/plugin/environment-error.js +22 -0
  32. package/dist/plugin/mcp-oauth.d.ts +10 -0
  33. package/dist/plugin/mcp-oauth.js +24 -0
  34. package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
  35. package/dist/plugin/sandbox-upload-fetch.js +22 -14
  36. package/dist/scss.d.js +1 -1
  37. package/dist/storage-content-api/api-types.d.ts +22 -1
  38. package/dist/storage-content-api/api-types.js +2 -1
  39. package/dist/storage-content-api/client.d.ts +3 -3
  40. package/dist/storage-content-api/client.js +13 -35
  41. package/dist/storage-content-api/index.js +20 -21
  42. package/dist/storage-content-api/staticHandler.js +4 -1
  43. package/dist/storage-content-api/types.d.ts +2 -2
  44. package/dist/utils/env-management.js +7 -0
  45. package/package.json +21 -23
  46. package/dist/db-content-api/utilities/auth.d.ts +0 -29
  47. package/dist/db-content-api/utilities/auth.js +0 -82
@@ -1,5 +1,6 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
1
3
  import { APIError, createDatabaseAdapter, ValidationError } from 'payload';
2
- import { v4 as uuid } from 'uuid';
3
4
  import { FigmaApiError } from '../api/figma-api.js';
4
5
  import { CONTENT_SYSTEM_NOT_FOUND_MESSAGE } from '../constants.js';
5
6
  import { createContentApiClient } from '../content-api/createContentApiClient.js';
@@ -8,6 +9,7 @@ import { getGlobalSlug } from './temp-utilities/slug.js';
8
9
  import { addFallbackSort } from './temp-utilities/sorting.js';
9
10
  import { unwrapDocument, unwrapFindResponse } from './temp-utilities/unwrapDocument.js';
10
11
  import { getClientVersionHeaders } from './utilities/clientVersionHeaders.js';
12
+ import { getCorrelationHeaders } from './utilities/correlationIds.js';
11
13
  import { dataToContentAPI, resolveVersionContent } from './utilities/data/index.js';
12
14
  import { injectGlobalType } from './utilities/data/injectGlobalType.js';
13
15
  import { validateRelationshipIds } from './utilities/data/validateRelationships.js';
@@ -38,6 +40,7 @@ async function syncCollections() {
38
40
  let existingIds;
39
41
  try {
40
42
  const { data: response, error, response: httpResponse } = await this.client.GET('/api/v0/content_systems/{contentSystemId}/collections', {
43
+ headers: getCorrelationHeaders(),
41
44
  params: {
42
45
  path: {
43
46
  contentSystemId: this.contentSystemId
@@ -103,6 +106,7 @@ async function createCollection(collectionId) {
103
106
  body: {
104
107
  id: collectionId
105
108
  },
109
+ headers: getCorrelationHeaders(),
106
110
  params: {
107
111
  path: {
108
112
  contentSystemId: this.contentSystemId
@@ -120,7 +124,7 @@ async function createCollection(collectionId) {
120
124
  }
121
125
  }
122
126
  }
123
- 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 }) {
124
128
  const locale = addFallbackLocale(localeArg, this.payload);
125
129
  const localeNormalizedWhere = normalizeLocaleInWhere(where, this.payload, collection, locale);
126
130
  const joinClause = convertPayloadJoinsToContentAPI(this.payload, collection, joins);
@@ -135,7 +139,8 @@ async function findMany({ collection, joins, limit, locale: localeArg, page, pag
135
139
  schema: this.documentSchema(),
136
140
  sort: addFallbackSort(sort, this.payload, collection),
137
141
  where: convertPayloadWhereToContentAPI(localeNormalizedWhere, this.payload, collection, false)
138
- }
142
+ },
143
+ headers: getCorrelationHeaders(req)
139
144
  });
140
145
  if (error) {
141
146
  throw createDocumentContentAPIError(this, 'findMany', error, httpResponse.status, collection);
@@ -159,6 +164,7 @@ async function find(args) {
159
164
  locale: args.locale,
160
165
  page: args.page ?? 1,
161
166
  pagination: args.pagination,
167
+ req: args.req,
162
168
  sort: args.sort || collectionConfig?.defaultSort,
163
169
  where: args.where
164
170
  });
@@ -180,7 +186,8 @@ async function findVersions(args) {
180
186
  schema: this.documentSchema(),
181
187
  sort: sortWithFallback,
182
188
  where: whereClause
183
- }
189
+ },
190
+ headers: getCorrelationHeaders(args.req)
184
191
  });
185
192
  if (error) {
186
193
  throw createDocumentContentAPIError(this, 'findVersions', error, httpResponse.status, args.collection);
@@ -197,6 +204,7 @@ async function queryDrafts(args) {
197
204
  locale: args.locale,
198
205
  page: args.page,
199
206
  pagination: args.pagination,
207
+ req: args.req,
200
208
  sort: args.sort,
201
209
  where: {
202
210
  ...args.where,
@@ -239,7 +247,8 @@ async function createVersion(args) {
239
247
  updatedAt: args.updatedAt,
240
248
  version: versionContent
241
249
  }
242
- }
250
+ },
251
+ headers: getCorrelationHeaders(args.req)
243
252
  });
244
253
  if (error) {
245
254
  throw createDocumentContentAPIError(this, 'createVersion', error, httpResponse.status, args.collectionSlug);
@@ -282,7 +291,8 @@ async function updateVersion(args) {
282
291
  version: versionContent
283
292
  },
284
293
  where: convertPayloadWhereToContentAPI(where, this.payload, args.collection, true)
285
- }
294
+ },
295
+ headers: getCorrelationHeaders(args.req)
286
296
  });
287
297
  if (error) {
288
298
  throw createDocumentContentAPIError(this, 'updateVersion', error, httpResponse.status, args.collection);
@@ -317,7 +327,8 @@ async function deleteVersions(args) {
317
327
  locale,
318
328
  schema: this.documentSchema(),
319
329
  where: convertPayloadWhereToContentAPI(args.where, this.payload, collection, true)
320
- }
330
+ },
331
+ headers: getCorrelationHeaders(args.req)
321
332
  });
322
333
  if (error) {
323
334
  throw createDocumentContentAPIError(this, 'deleteVersions', error, httpResponse.status, collection);
@@ -330,6 +341,7 @@ async function findOne(args) {
330
341
  limit: 1,
331
342
  locale: args.locale,
332
343
  pagination: false,
344
+ req: args.req,
333
345
  where: args.where
334
346
  });
335
347
  return docs[0] ?? null;
@@ -347,7 +359,8 @@ async function findDistinct(args) {
347
359
  schema: this.documentSchema(),
348
360
  sort: addFallbackSort(args.sort, this.payload, args.collection),
349
361
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
350
- }
362
+ },
363
+ headers: getCorrelationHeaders(args.req)
351
364
  });
352
365
  if (error) {
353
366
  throw createDocumentContentAPIError(this, 'findDistinct', error, httpResponse.status, args.collection);
@@ -380,7 +393,8 @@ async function updateMany(args) {
380
393
  schema: this.documentSchema(),
381
394
  sort: addFallbackSort(args.sort || '-updatedAt', this.payload, args.collection),
382
395
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
383
- }
396
+ },
397
+ headers: getCorrelationHeaders(args.req)
384
398
  });
385
399
  if (error) {
386
400
  throw createDocumentContentAPIError(this, 'updateMany', error, httpResponse.status, args.collection);
@@ -420,7 +434,8 @@ async function updateOne(args) {
420
434
  locale,
421
435
  schema: this.documentSchema(),
422
436
  where: convertPayloadWhereToContentAPI(where, this.payload, args.collection, false)
423
- }
437
+ },
438
+ headers: getCorrelationHeaders(args.req)
424
439
  });
425
440
  if (error) {
426
441
  throw createDocumentContentAPIError(this, 'updateOne', error, httpResponse.status, args.collection);
@@ -452,7 +467,8 @@ async function deleteMany(args) {
452
467
  locale,
453
468
  schema: this.documentSchema(),
454
469
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
455
- }
470
+ },
471
+ headers: getCorrelationHeaders(args.req)
456
472
  });
457
473
  if (error) {
458
474
  throw createDocumentContentAPIError(this, 'deleteMany', error, httpResponse.status, args.collection);
@@ -468,7 +484,8 @@ async function deleteOne(args) {
468
484
  locale,
469
485
  schema: this.documentSchema(),
470
486
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
471
- }
487
+ },
488
+ headers: getCorrelationHeaders(args.req)
472
489
  });
473
490
  if (error) {
474
491
  throw createDocumentContentAPIError(this, 'deleteOne', error, httpResponse.status, args.collection);
@@ -500,7 +517,7 @@ async function create(args) {
500
517
  } else if ((isGlobalCollection || customIDType || this.allowIDOnCreate) && args.data.id != null && (typeof args.data.id === 'string' || typeof args.data.id === 'number')) {
501
518
  id = String(args.data.id);
502
519
  } else {
503
- id = uuid();
520
+ id = randomUUID();
504
521
  }
505
522
  const locale = addFallbackLocale(args.locale, this.payload);
506
523
  validateRelationshipIds({
@@ -522,7 +539,8 @@ async function create(args) {
522
539
  environmentName: this.environmentName,
523
540
  locale,
524
541
  schema: this.documentSchema()
525
- }
542
+ },
543
+ headers: getCorrelationHeaders(args.req)
526
544
  });
527
545
  if (error) {
528
546
  redirectInitialAutosaveCreate({
@@ -550,7 +568,8 @@ async function clearDatabase() {
550
568
  const response = await fetch(getClearDatabaseUrl(this.url, process.env.FIGMA_CONTENT_API_CUTOVER_STATE), {
551
569
  headers: {
552
570
  'Content-Type': 'application/json',
553
- ...this.clientVersionHeaders
571
+ ...this.clientVersionHeaders,
572
+ ...getCorrelationHeaders()
554
573
  },
555
574
  method: 'POST'
556
575
  });
@@ -572,7 +591,43 @@ export function getClearDatabaseUrl(url, cutoverState) {
572
591
  }
573
592
  return clearDatabaseUrl.toString();
574
593
  }
594
+ async function countJobsForHandleSchedules(args) {
595
+ if (args.collection !== 'payload-jobs') {
596
+ return undefined;
597
+ }
598
+ // Payload's /handle-schedules counts unfinished jobs before queuing another occurrence.
599
+ // Until v1 supports error and meta.scheduled JSON filters, apply those filters locally.
600
+ const countFilters = args.where?.and ?? [];
601
+ const noErrorFilter = countFilters.find((filter)=>isDeepStrictEqual(filter, {
602
+ error: {
603
+ exists: false
604
+ }
605
+ }));
606
+ if (!noErrorFilter) {
607
+ return undefined;
608
+ }
609
+ const onlyScheduledJobsFilter = countFilters.find((filter)=>isDeepStrictEqual(filter, {
610
+ 'meta.scheduled': {
611
+ equals: true
612
+ }
613
+ }));
614
+ const { docs } = await this.find({
615
+ ...args,
616
+ limit: 0,
617
+ where: {
618
+ ...args.where,
619
+ and: countFilters.filter((filter)=>filter !== noErrorFilter && filter !== onlyScheduledJobsFilter)
620
+ }
621
+ });
622
+ return {
623
+ totalDocs: docs.filter((job)=>job.error == null && (!onlyScheduledJobsFilter || job.meta?.scheduled === true)).length
624
+ };
625
+ }
575
626
  async function count(args) {
627
+ const handleSchedulesCount = await countJobsForHandleSchedules.call(this, args);
628
+ if (handleSchedulesCount) {
629
+ return handleSchedulesCount;
630
+ }
576
631
  const locale = addFallbackLocale(args.locale, this.payload);
577
632
  const { data: response, error, response: httpResponse } = await this.client.POST('/api/v1/documents:count', {
578
633
  body: {
@@ -581,7 +636,8 @@ async function count(args) {
581
636
  locale,
582
637
  schema: this.documentSchema(),
583
638
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
584
- }
639
+ },
640
+ headers: getCorrelationHeaders(args.req)
585
641
  });
586
642
  if (error) {
587
643
  throw createDocumentContentAPIError(this, 'count', error, httpResponse.status, args.collection);
@@ -602,7 +658,8 @@ async function countVersions(args) {
602
658
  locale,
603
659
  schema: this.documentSchema(),
604
660
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, true)
605
- }
661
+ },
662
+ headers: getCorrelationHeaders(args.req)
606
663
  });
607
664
  if (error) {
608
665
  throw createDocumentContentAPIError(this, 'countVersions', error, httpResponse.status, args.collection);
@@ -630,7 +687,7 @@ async function upsert(args) {
630
687
  }
631
688
  }
632
689
  if (!documentId) {
633
- documentId = uuid();
690
+ documentId = randomUUID();
634
691
  }
635
692
  const locale = addFallbackLocale(args.locale, this.payload);
636
693
  validateRelationshipIds({
@@ -659,7 +716,8 @@ async function upsert(args) {
659
716
  locale,
660
717
  schema: this.documentSchema(),
661
718
  where: convertPayloadWhereToContentAPI(args.where, this.payload, args.collection, false)
662
- }
719
+ },
720
+ headers: getCorrelationHeaders(args.req)
663
721
  });
664
722
  if (error) {
665
723
  throw createDocumentContentAPIError(this, 'upsert', error, httpResponse.status, args.collection);
@@ -719,7 +777,8 @@ async function updateJobs(args) {
719
777
  schema: this.documentSchema(),
720
778
  sort: sortClause,
721
779
  where: whereQuery
722
- }
780
+ },
781
+ headers: getCorrelationHeaders(args.req)
723
782
  });
724
783
  if (error) {
725
784
  throw createDocumentContentAPIError(this, 'updateJobs', error, httpResponse.status, collection);
@@ -751,6 +810,7 @@ async function createGlobal(args) {
751
810
  ...args.data,
752
811
  id: args.slug
753
812
  },
813
+ req: args.req,
754
814
  where: {
755
815
  id: {
756
816
  equals: args.slug
@@ -763,6 +823,7 @@ async function findGlobal(args) {
763
823
  const doc = await this.findOne({
764
824
  collection: getGlobalSlug(args.slug),
765
825
  locale: args.locale,
826
+ req: args.req,
766
827
  where: args.where ?? {}
767
828
  });
768
829
  return injectGlobalType(doc, args.slug);
@@ -771,6 +832,7 @@ async function updateGlobal(args) {
771
832
  const doc = await this.upsert({
772
833
  collection: getGlobalSlug(args.slug),
773
834
  data: args.data,
835
+ req: args.req,
774
836
  where: {
775
837
  id: {
776
838
  equals: args.slug
@@ -787,6 +849,7 @@ function findGlobalVersions(args) {
787
849
  locale: args.locale,
788
850
  page: args.page,
789
851
  pagination: args.pagination,
852
+ req: args.req,
790
853
  sort: args.sort,
791
854
  where: args.where
792
855
  });
@@ -800,6 +863,7 @@ function createGlobalVersion(args) {
800
863
  createdAt: args.createdAt,
801
864
  parent: args.globalSlug,
802
865
  publishedLocale: args.publishedLocale,
866
+ req: args.req,
803
867
  updatedAt: args.updatedAt,
804
868
  versionData: args.versionData
805
869
  });
@@ -811,6 +875,7 @@ function updateGlobalVersion(args) {
811
875
  id: args.id,
812
876
  collection: getGlobalSlug(args.global),
813
877
  locale: args.locale,
878
+ req: args.req,
814
879
  versionData: args.versionData
815
880
  });
816
881
  }
@@ -818,6 +883,7 @@ function updateGlobalVersion(args) {
818
883
  return this.updateVersion({
819
884
  collection: getGlobalSlug(args.global),
820
885
  locale: args.locale,
886
+ req: args.req,
821
887
  versionData: args.versionData,
822
888
  where: args.where
823
889
  });
@@ -826,6 +892,7 @@ function countGlobalVersions(args) {
826
892
  return this.countVersions({
827
893
  collection: getGlobalSlug(args.global),
828
894
  locale: args.locale,
895
+ req: args.req,
829
896
  where: args.where
830
897
  });
831
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
+ }
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,5 +1,5 @@
1
+ import crypto from 'crypto';
1
2
  import { parseCookies } from 'payload';
2
- import { v4 as uuid } from 'uuid';
3
3
  import { hasUserTokenPropsChanged } from './utilities/hasUserTokenPropsChanged.js';
4
4
  import { isDuplicateKeyError } from './utilities/isDuplicateKeyError.js';
5
5
  export const DEFAULT_USER_INFO_COOKIE_NAME = 'figma-user-info';
@@ -95,7 +95,7 @@ export const defaultVerify = ({ collection, strategyName, userInfoCookieName = D
95
95
  }
96
96
  };
97
97
  if (typeof collection.auth === 'object' && !collection.auth.disableLocalStrategy) {
98
- newUser.password = uuid();
98
+ newUser.password = crypto.randomUUID();
99
99
  }
100
100
  try {
101
101
  user = await payload.create({
@@ -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>;