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

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 (45) 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 +40 -3
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.js +1 -0
  10. package/dist/oauth/defaults.js +2 -2
  11. package/dist/oauth/hooks/me.d.ts +4 -3
  12. package/dist/oauth/hooks/me.js +6 -52
  13. package/dist/oauth/hooks/refresh.js +9 -1
  14. package/dist/oauth/index.js +1 -1
  15. package/dist/oauth/strategy/index.d.ts +3 -0
  16. package/dist/oauth/strategy/index.js +49 -3
  17. package/dist/oauth/utilities/clearCookie.d.ts +1 -0
  18. package/dist/oauth/utilities/clearCookie.js +13 -9
  19. package/dist/oauth/utilities/clearSessionCookies.d.ts +5 -0
  20. package/dist/oauth/utilities/clearSessionCookies.js +17 -0
  21. package/dist/oauth/utilities/getAuthorizeURL.js +1 -2
  22. package/dist/oauth/utilities/mergeHeaders.js +11 -23
  23. package/dist/oauth/utilities/refreshTokens.d.ts +9 -3
  24. package/dist/oauth/utilities/refreshTokens.js +45 -34
  25. package/dist/plugin/build-config.js +10 -7
  26. package/dist/plugin/dev-cookie-names.d.ts +4 -1
  27. package/dist/plugin/dev-cookie-names.js +6 -3
  28. package/dist/plugin/environment-error.d.ts +4 -0
  29. package/dist/plugin/environment-error.js +22 -0
  30. package/dist/plugin/mcp-oauth.d.ts +10 -0
  31. package/dist/plugin/mcp-oauth.js +24 -0
  32. package/dist/plugin/sandbox-upload-fetch.d.ts +5 -6
  33. package/dist/plugin/sandbox-upload-fetch.js +22 -14
  34. package/dist/scss.d.js +1 -1
  35. package/dist/storage-content-api/api-types.d.ts +22 -1
  36. package/dist/storage-content-api/api-types.js +2 -1
  37. package/dist/storage-content-api/client.d.ts +3 -3
  38. package/dist/storage-content-api/client.js +13 -35
  39. package/dist/storage-content-api/index.js +20 -21
  40. package/dist/storage-content-api/staticHandler.js +4 -1
  41. package/dist/storage-content-api/types.d.ts +2 -2
  42. package/dist/utils/env-management.js +7 -0
  43. package/package.json +20 -22
  44. package/dist/db-content-api/utilities/auth.d.ts +0 -29
  45. 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
  });
@@ -6242,6 +6242,171 @@ export type paths = {
6242
6242
  patch?: never;
6243
6243
  trace?: never;
6244
6244
  };
6245
+ '/api/v0/uploads/transform/sign': {
6246
+ parameters: {
6247
+ query?: never;
6248
+ header?: never;
6249
+ path?: never;
6250
+ cookie?: never;
6251
+ };
6252
+ get?: never;
6253
+ put?: never;
6254
+ post: {
6255
+ parameters: {
6256
+ query?: never;
6257
+ header?: never;
6258
+ path?: never;
6259
+ cookie?: never;
6260
+ };
6261
+ requestBody?: {
6262
+ content: {
6263
+ 'application/json': components['schemas']['SignImageTransformRequest'];
6264
+ };
6265
+ };
6266
+ responses: {
6267
+ /** @description Image transform path signed */
6268
+ 200: {
6269
+ headers: {
6270
+ [name: string]: unknown;
6271
+ };
6272
+ content: {
6273
+ 'application/json': components['schemas']['SignImageTransformResponse'];
6274
+ };
6275
+ };
6276
+ /** @description Bad Request */
6277
+ 400: {
6278
+ headers: {
6279
+ [name: string]: unknown;
6280
+ };
6281
+ content: {
6282
+ 'application/json': {
6283
+ /** @example Error message describing the issue. */
6284
+ message: string;
6285
+ /** @example database.constraint_violation */
6286
+ code?: string;
6287
+ /** @example email */
6288
+ field?: string;
6289
+ /** @example unique_constraint */
6290
+ constraint?: string;
6291
+ };
6292
+ };
6293
+ };
6294
+ /** @description Unauthorized */
6295
+ 401: {
6296
+ headers: {
6297
+ [name: string]: unknown;
6298
+ };
6299
+ content: {
6300
+ 'application/json': {
6301
+ /** @example Error message describing the issue. */
6302
+ message: string;
6303
+ /** @example database.constraint_violation */
6304
+ code?: string;
6305
+ /** @example email */
6306
+ field?: string;
6307
+ /** @example unique_constraint */
6308
+ constraint?: string;
6309
+ };
6310
+ };
6311
+ };
6312
+ /** @description Forbidden */
6313
+ 403: {
6314
+ headers: {
6315
+ [name: string]: unknown;
6316
+ };
6317
+ content: {
6318
+ 'application/json': {
6319
+ /** @example Error message describing the issue. */
6320
+ message: string;
6321
+ /** @example database.constraint_violation */
6322
+ code?: string;
6323
+ /** @example email */
6324
+ field?: string;
6325
+ /** @example unique_constraint */
6326
+ constraint?: string;
6327
+ };
6328
+ };
6329
+ };
6330
+ /** @description Not Found */
6331
+ 404: {
6332
+ headers: {
6333
+ [name: string]: unknown;
6334
+ };
6335
+ content: {
6336
+ 'application/json': {
6337
+ /** @example Error message describing the issue. */
6338
+ message: string;
6339
+ /** @example database.constraint_violation */
6340
+ code?: string;
6341
+ /** @example email */
6342
+ field?: string;
6343
+ /** @example unique_constraint */
6344
+ constraint?: string;
6345
+ };
6346
+ };
6347
+ };
6348
+ /** @description Content system rate limit exceeded */
6349
+ 429: {
6350
+ headers: {
6351
+ [name: string]: unknown;
6352
+ };
6353
+ content: {
6354
+ 'application/json': {
6355
+ /** @example Error message describing the issue. */
6356
+ message: string;
6357
+ /** @example database.constraint_violation */
6358
+ code?: string;
6359
+ /** @example email */
6360
+ field?: string;
6361
+ /** @example unique_constraint */
6362
+ constraint?: string;
6363
+ };
6364
+ };
6365
+ };
6366
+ /** @description Internal Server Error */
6367
+ 500: {
6368
+ headers: {
6369
+ [name: string]: unknown;
6370
+ };
6371
+ content: {
6372
+ 'application/json': {
6373
+ /** @example Error message describing the issue. */
6374
+ message: string;
6375
+ /** @example database.constraint_violation */
6376
+ code?: string;
6377
+ /** @example email */
6378
+ field?: string;
6379
+ /** @example unique_constraint */
6380
+ constraint?: string;
6381
+ };
6382
+ };
6383
+ };
6384
+ /** @description Service Unavailable */
6385
+ 503: {
6386
+ headers: {
6387
+ [name: string]: unknown;
6388
+ };
6389
+ content: {
6390
+ 'application/json': {
6391
+ /** @example Error message describing the issue. */
6392
+ message: string;
6393
+ /** @example database.constraint_violation */
6394
+ code?: string;
6395
+ /** @example email */
6396
+ field?: string;
6397
+ /** @example unique_constraint */
6398
+ constraint?: string;
6399
+ };
6400
+ };
6401
+ };
6402
+ };
6403
+ };
6404
+ delete?: never;
6405
+ options?: never;
6406
+ head?: never;
6407
+ patch?: never;
6408
+ trace?: never;
6409
+ };
6245
6410
  };
6246
6411
  export type webhooks = Record<string, never>;
6247
6412
  export type components = {
@@ -8208,6 +8373,88 @@ export type components = {
8208
8373
  */
8209
8374
  content_system_id?: string;
8210
8375
  };
8376
+ SignImageTransformRequest: {
8377
+ collectionId: string;
8378
+ filename: string;
8379
+ /** @description Stored MIME type supplied by Payload after file resolution and access checks */
8380
+ mimeType: string;
8381
+ /**
8382
+ * @default GET
8383
+ * @enum {string}
8384
+ */
8385
+ method: 'GET' | 'HEAD';
8386
+ size?: {
8387
+ name: string;
8388
+ anim?: boolean;
8389
+ background?: string;
8390
+ blur?: number;
8391
+ border?: {
8392
+ color: string;
8393
+ width: number;
8394
+ } | {
8395
+ color: string;
8396
+ bottom: number;
8397
+ left: number;
8398
+ right: number;
8399
+ top: number;
8400
+ };
8401
+ brightness?: number;
8402
+ /** @enum {string} */
8403
+ compression?: 'fast';
8404
+ contrast?: number;
8405
+ dpr?: number;
8406
+ /** @enum {string} */
8407
+ fit?: 'contain' | 'cover' | 'crop' | 'pad' | 'scale-down' | 'scale-up' | 'squeeze';
8408
+ /** @enum {string} */
8409
+ flip?: 'h' | 'hv' | 'v';
8410
+ /** @enum {string} */
8411
+ format?: 'avif' | 'baseline-jpeg' | 'jpeg' | 'png' | 'png-force' | 'webp';
8412
+ gamma?: number;
8413
+ gravity?: ('auto' | 'bottom' | 'center' | 'entropy' | 'face' | 'left' | 'right' | 'top') | {
8414
+ /** @enum {string} */
8415
+ mode?: 'box-center' | 'remainder';
8416
+ x?: number;
8417
+ y?: number;
8418
+ };
8419
+ height?: number;
8420
+ /** @enum {string} */
8421
+ metadata?: 'copyright' | 'keep' | 'none';
8422
+ quality?: number | ('high' | 'medium-high' | 'medium-low' | 'low');
8423
+ rotate?: 90 | 180 | 270;
8424
+ saturation?: number;
8425
+ /** @enum {string} */
8426
+ segment?: 'foreground';
8427
+ sharpen?: number;
8428
+ trim?: 'border' | {
8429
+ border?: boolean | {
8430
+ color?: string;
8431
+ keep?: number;
8432
+ tolerance?: number;
8433
+ };
8434
+ bottom?: number;
8435
+ height?: number;
8436
+ left?: number;
8437
+ right?: number;
8438
+ top?: number;
8439
+ width?: number;
8440
+ };
8441
+ /** @enum {string} */
8442
+ upscale?: 'generate' | 'interpolate';
8443
+ width?: number;
8444
+ zoom?: number;
8445
+ };
8446
+ request?: {
8447
+ w?: number;
8448
+ q?: number;
8449
+ };
8450
+ responseHeaders?: {
8451
+ /** @example public, max-age=3600 */
8452
+ cacheControl: string;
8453
+ };
8454
+ };
8455
+ SignImageTransformResponse: {
8456
+ path: string;
8457
+ };
8211
8458
  };
8212
8459
  responses: never;
8213
8460
  parameters: never;
@@ -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';
@@ -500,7 +501,7 @@ async function create(args) {
500
501
  } else if ((isGlobalCollection || customIDType || this.allowIDOnCreate) && args.data.id != null && (typeof args.data.id === 'string' || typeof args.data.id === 'number')) {
501
502
  id = String(args.data.id);
502
503
  } else {
503
- id = uuid();
504
+ id = randomUUID();
504
505
  }
505
506
  const locale = addFallbackLocale(args.locale, this.payload);
506
507
  validateRelationshipIds({
@@ -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: {
@@ -630,7 +667,7 @@ async function upsert(args) {
630
667
  }
631
668
  }
632
669
  if (!documentId) {
633
- documentId = uuid();
670
+ documentId = randomUUID();
634
671
  }
635
672
  const locale = addFallbackLocale(args.locale, this.payload);
636
673
  validateRelationshipIds({
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>;