@payloadcms/figma 0.0.1-alpha.4 → 0.0.1-alpha.41
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.
- package/dist/api/control-plane.d.ts +22 -1
- package/dist/api/control-plane.d.ts.map +1 -1
- package/dist/api/control-plane.js +55 -22
- package/dist/api/control-plane.js.map +1 -1
- package/dist/api/figma-api.d.ts.map +1 -1
- package/dist/api/figma-api.js +45 -26
- package/dist/api/figma-api.js.map +1 -1
- package/dist/auth/callback-server.d.ts.map +1 -1
- package/dist/auth/callback-server.js +2 -1
- package/dist/auth/callback-server.js.map +1 -1
- package/dist/auth/crypto-utils.d.ts.map +1 -1
- package/dist/auth/crypto-utils.js +5 -5
- package/dist/auth/crypto-utils.js.map +1 -1
- package/dist/auth/jwt-validator.d.ts +2 -1
- package/dist/auth/jwt-validator.d.ts.map +1 -1
- package/dist/auth/jwt-validator.js +2 -2
- package/dist/auth/jwt-validator.js.map +1 -1
- package/dist/auth/oauth-flow.d.ts +1 -1
- package/dist/auth/oauth-flow.d.ts.map +1 -1
- package/dist/auth/oauth-flow.js +9 -8
- package/dist/auth/oauth-flow.js.map +1 -1
- package/dist/auth/project-token.d.ts.map +1 -1
- package/dist/auth/project-token.js +9 -4
- package/dist/auth/project-token.js.map +1 -1
- package/dist/auth/refresh.d.ts.map +1 -1
- package/dist/auth/refresh.js +14 -9
- package/dist/auth/refresh.js.map +1 -1
- package/dist/auth/token-store.d.ts +10 -0
- package/dist/auth/token-store.d.ts.map +1 -1
- package/dist/auth/token-store.js +20 -0
- package/dist/auth/token-store.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +31 -0
- package/dist/cli.js.map +1 -1
- package/dist/commands/build-lambda-zip.d.ts +5 -0
- package/dist/commands/build-lambda-zip.d.ts.map +1 -0
- package/dist/commands/build-lambda-zip.js +19 -0
- package/dist/commands/build-lambda-zip.js.map +1 -0
- package/dist/commands/deploy.d.ts +4 -0
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +71 -129
- package/dist/commands/deploy.js.map +1 -1
- package/dist/commands/init.d.ts +1 -5
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +94 -85
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/list-tokens.d.ts.map +1 -1
- package/dist/commands/list-tokens.js +6 -3
- package/dist/commands/list-tokens.js.map +1 -1
- package/dist/commands/login.d.ts +8 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +21 -11
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/logout.js +2 -2
- package/dist/commands/logout.js.map +1 -1
- package/dist/config/oauth.d.ts +4 -14
- package/dist/config/oauth.d.ts.map +1 -1
- package/dist/config/oauth.js +19 -40
- package/dist/config/oauth.js.map +1 -1
- package/dist/constants.d.ts +26 -18
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +34 -20
- package/dist/constants.js.map +1 -1
- package/dist/db-content-api/README.md +98 -0
- package/dist/db-content-api/generated/content-api-types.d.ts +3854 -0
- package/dist/db-content-api/generated/content-api-types.d.ts.map +1 -0
- package/dist/db-content-api/generated/content-api-types.js +7 -0
- package/dist/db-content-api/generated/content-api-types.js.map +1 -0
- package/dist/db-content-api/index.d.ts +18 -0
- package/dist/db-content-api/index.d.ts.map +1 -0
- package/dist/db-content-api/index.js +578 -0
- package/dist/db-content-api/index.js.map +1 -0
- package/dist/db-content-api/temp-utilities/pagination.d.ts +13 -0
- package/dist/db-content-api/temp-utilities/pagination.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/pagination.js +45 -0
- package/dist/db-content-api/temp-utilities/pagination.js.map +1 -0
- package/dist/db-content-api/temp-utilities/slug.d.ts +2 -0
- package/dist/db-content-api/temp-utilities/slug.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/slug.js +3 -0
- package/dist/db-content-api/temp-utilities/slug.js.map +1 -0
- package/dist/db-content-api/temp-utilities/sorting.d.ts +3 -0
- package/dist/db-content-api/temp-utilities/sorting.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/sorting.js +32 -0
- package/dist/db-content-api/temp-utilities/sorting.js.map +1 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts +4 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts.map +1 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.js +53 -0
- package/dist/db-content-api/temp-utilities/unwrapDocument.js.map +1 -0
- package/dist/db-content-api/utilities/auth.d.ts +30 -0
- package/dist/db-content-api/utilities/auth.d.ts.map +1 -0
- package/dist/db-content-api/utilities/auth.js +81 -0
- package/dist/db-content-api/utilities/auth.js.map +1 -0
- package/dist/db-content-api/utilities/data/applyDefaults.d.ts +7 -0
- package/dist/db-content-api/utilities/data/applyDefaults.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/applyDefaults.js +59 -0
- package/dist/db-content-api/utilities/data/applyDefaults.js.map +1 -0
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts +11 -0
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/castFieldValue.js +66 -0
- package/dist/db-content-api/utilities/data/castFieldValue.js.map +1 -0
- package/dist/db-content-api/utilities/data/index.d.ts +30 -0
- package/dist/db-content-api/utilities/data/index.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/index.js +182 -0
- package/dist/db-content-api/utilities/data/index.js.map +1 -0
- package/dist/db-content-api/utilities/data/removeVirtualFields.d.ts +12 -0
- package/dist/db-content-api/utilities/data/removeVirtualFields.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/removeVirtualFields.js +54 -0
- package/dist/db-content-api/utilities/data/removeVirtualFields.js.map +1 -0
- package/dist/db-content-api/utilities/data/stripFields.d.ts +48 -0
- package/dist/db-content-api/utilities/data/stripFields.d.ts.map +1 -0
- package/dist/db-content-api/utilities/data/stripFields.js +195 -0
- package/dist/db-content-api/utilities/data/stripFields.js.map +1 -0
- package/dist/db-content-api/utilities/joins.d.ts +55 -0
- package/dist/db-content-api/utilities/joins.d.ts.map +1 -0
- package/dist/db-content-api/utilities/joins.js +136 -0
- package/dist/db-content-api/utilities/joins.js.map +1 -0
- package/dist/db-content-api/utilities/where.d.ts +12 -0
- package/dist/db-content-api/utilities/where.d.ts.map +1 -0
- package/dist/db-content-api/utilities/where.js +107 -0
- package/dist/db-content-api/utilities/where.js.map +1 -0
- package/dist/endpoints/health.d.ts +3 -0
- package/dist/endpoints/health.d.ts.map +1 -0
- package/dist/endpoints/health.js +11 -0
- package/dist/endpoints/health.js.map +1 -0
- package/dist/exports/client.d.ts +4 -0
- package/dist/exports/client.d.ts.map +1 -0
- package/dist/exports/client.js +5 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/oauth/components/LoginButton/index.d.ts.map +1 -1
- package/dist/oauth/components/LoginButton/index.js +50 -6
- package/dist/oauth/components/LoginButton/index.js.map +1 -1
- package/dist/oauth/components/LoginButton/index.scss +50 -3
- package/dist/oauth/components/LogoutButton/index.d.ts.map +1 -1
- package/dist/oauth/components/LogoutButton/index.js +0 -1
- package/dist/oauth/components/LogoutButton/index.js.map +1 -1
- package/dist/oauth/defaults.d.ts.map +1 -1
- package/dist/oauth/defaults.js +29 -5
- package/dist/oauth/defaults.js.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.d.ts.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.js +4 -4
- package/dist/oauth/endpoints/getLoginEndpoint.js.map +1 -1
- package/dist/oauth/index.d.ts.map +1 -1
- package/dist/oauth/index.js +42 -7
- package/dist/oauth/index.js.map +1 -1
- package/dist/oauth/strategy/index.d.ts +0 -2
- package/dist/oauth/strategy/index.d.ts.map +1 -1
- package/dist/oauth/strategy/index.js +38 -15
- package/dist/oauth/strategy/index.js.map +1 -1
- package/dist/oauth/types.d.ts +6 -6
- package/dist/oauth/types.d.ts.map +1 -1
- package/dist/oauth/types.js.map +1 -1
- package/dist/oauth/utilities/createCookieOptions.d.ts.map +1 -1
- package/dist/oauth/utilities/createCookieOptions.js.map +1 -1
- package/dist/oauth/utilities/isDuplicateKeyError.d.ts +7 -0
- package/dist/oauth/utilities/isDuplicateKeyError.d.ts.map +1 -0
- package/dist/oauth/utilities/isDuplicateKeyError.js +14 -0
- package/dist/oauth/utilities/isDuplicateKeyError.js.map +1 -0
- package/dist/oauth/utilities/refreshTokens.d.ts.map +1 -1
- package/dist/oauth/utilities/refreshTokens.js +1 -1
- package/dist/oauth/utilities/refreshTokens.js.map +1 -1
- package/dist/plugin/build-config.d.ts +21 -4
- package/dist/plugin/build-config.d.ts.map +1 -1
- package/dist/plugin/build-config.js +114 -8
- package/dist/plugin/build-config.js.map +1 -1
- package/dist/storage-content-api/api-types.d.ts +161 -0
- package/dist/storage-content-api/api-types.d.ts.map +1 -0
- package/dist/storage-content-api/api-types.js +6 -0
- package/dist/storage-content-api/api-types.js.map +1 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts +9 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts.map +1 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js +42 -0
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js.map +1 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts +13 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts.map +1 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.js +31 -0
- package/dist/storage-content-api/client-uploads/generateSignedURL.js.map +1 -0
- package/dist/storage-content-api/client.d.ts +6 -0
- package/dist/storage-content-api/client.d.ts.map +1 -0
- package/dist/storage-content-api/client.js +36 -0
- package/dist/storage-content-api/client.js.map +1 -0
- package/dist/storage-content-api/generateURL.d.ts +7 -0
- package/dist/storage-content-api/generateURL.d.ts.map +1 -0
- package/dist/storage-content-api/generateURL.js +7 -0
- package/dist/storage-content-api/generateURL.js.map +1 -0
- package/dist/storage-content-api/handleDelete.d.ts +8 -0
- package/dist/storage-content-api/handleDelete.d.ts.map +1 -0
- package/dist/storage-content-api/handleDelete.js +15 -0
- package/dist/storage-content-api/handleDelete.js.map +1 -0
- package/dist/storage-content-api/handleUpload.d.ts +11 -0
- package/dist/storage-content-api/handleUpload.d.ts.map +1 -0
- package/dist/storage-content-api/handleUpload.js +136 -0
- package/dist/storage-content-api/handleUpload.js.map +1 -0
- package/dist/storage-content-api/index.d.ts +5 -0
- package/dist/storage-content-api/index.d.ts.map +1 -0
- package/dist/storage-content-api/index.js +31 -0
- package/dist/storage-content-api/index.js.map +1 -0
- package/dist/storage-content-api/staticHandler.d.ts +10 -0
- package/dist/storage-content-api/staticHandler.d.ts.map +1 -0
- package/dist/storage-content-api/staticHandler.js +55 -0
- package/dist/storage-content-api/staticHandler.js.map +1 -0
- package/dist/storage-content-api/types.d.ts +10 -0
- package/dist/storage-content-api/types.d.ts.map +1 -0
- package/dist/storage-content-api/types.js +3 -0
- package/dist/storage-content-api/types.js.map +1 -0
- package/dist/templates/README.md +19 -0
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/asset-collection.d.ts +3 -6
- package/dist/utils/asset-collection.d.ts.map +1 -1
- package/dist/utils/asset-collection.js +10 -34
- package/dist/utils/asset-collection.js.map +1 -1
- package/dist/utils/build-lambda-zip.d.ts +14 -0
- package/dist/utils/build-lambda-zip.d.ts.map +1 -0
- package/dist/utils/build-lambda-zip.js +81 -0
- package/dist/utils/build-lambda-zip.js.map +1 -0
- package/dist/utils/config.js +1 -1
- package/dist/utils/config.js.map +1 -1
- package/dist/utils/env-management.d.ts +9 -8
- package/dist/utils/env-management.d.ts.map +1 -1
- package/dist/utils/env-management.js +73 -74
- package/dist/utils/env-management.js.map +1 -1
- package/dist/utils/formatter.d.ts.map +1 -1
- package/dist/utils/formatter.js +3 -5
- package/dist/utils/formatter.js.map +1 -1
- package/dist/utils/lambda-config.d.ts +3 -1
- package/dist/utils/lambda-config.d.ts.map +1 -1
- package/dist/utils/lambda-config.js +13 -21
- package/dist/utils/lambda-config.js.map +1 -1
- package/dist/utils/messages.d.ts.map +1 -1
- package/dist/utils/messages.js +8 -7
- package/dist/utils/messages.js.map +1 -1
- package/dist/utils/payload-config-ast.d.ts +22 -3
- package/dist/utils/payload-config-ast.d.ts.map +1 -1
- package/dist/utils/payload-config-ast.js +89 -31
- package/dist/utils/payload-config-ast.js.map +1 -1
- package/dist/utils/payload-config-finder.d.ts +2 -2
- package/dist/utils/payload-config-finder.d.ts.map +1 -1
- package/dist/utils/payload-config-finder.js +48 -9
- package/dist/utils/payload-config-finder.js.map +1 -1
- package/dist/utils/payload-config-modifier.d.ts.map +1 -1
- package/dist/utils/payload-config-modifier.js +54 -6
- package/dist/utils/payload-config-modifier.js.map +1 -1
- package/dist/utils/payload-package-check.d.ts +12 -1
- package/dist/utils/payload-package-check.d.ts.map +1 -1
- package/dist/utils/payload-package-check.js +63 -5
- package/dist/utils/payload-package-check.js.map +1 -1
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +8 -5
- package/dist/utils/project.js.map +1 -1
- package/dist/utils/s3-upload.d.ts +0 -1
- package/dist/utils/s3-upload.d.ts.map +1 -1
- package/dist/utils/s3-upload.js +10 -3
- package/dist/utils/s3-upload.js.map +1 -1
- package/dist/utils/token-display.d.ts.map +1 -1
- package/dist/utils/token-display.js +11 -5
- package/dist/utils/token-display.js.map +1 -1
- package/dist/utils/typescript-validator.d.ts.map +1 -1
- package/dist/utils/typescript-validator.js +4 -6
- package/dist/utils/typescript-validator.js.map +1 -1
- package/dist/utils/version-check.d.ts +3 -0
- package/dist/utils/version-check.d.ts.map +1 -0
- package/dist/utils/version-check.js +38 -0
- package/dist/utils/version-check.js.map +1 -0
- package/package.json +31 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/strategy/index.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\n/* eslint-disable @typescript-eslint/restrict-template-expressions */\nimport type {\n AuthStrategyFunctionArgs,\n AuthStrategyResult,\n CollectionConfig,\n Payload,\n} from 'payload'\n\nimport * as jose from 'jose'\nimport { APIError, parseCookies } from 'payload'\n\nimport type { CollectionOptions, PluginOptions, VerifyFunction } from '../types.js'\n\nimport { JWTValidationError, validateProjectToken } from '../../auth/jwt-validator.js'\nimport { ProjectTokenError } from '../../auth/project-token.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createDebugLogger } from '../utilities/createDebugLogger.js'\nimport { getTokenExp } from '../utilities/getTokenExp.js'\nimport { mergeHeaders } from '../utilities/mergeHeaders.js'\nimport { refreshTokens } from '../utilities/refreshTokens.js'\n\nexport interface Options {\n clientID: string\n clientSecret?: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n debug?: boolean\n identityMetadata: string\n pluginOptions: PluginOptions\n strategyName: string\n verify: VerifyFunction\n}\n\nexport class Strategy {\n clientID: string\n clientSecret?: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n\n debug: boolean\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n debugLog: (...args: any[]) => void\n\n identityMetadataURL: string\n jwks?: {\n keys: jose.JWK[]\n }\n meta?: {\n authorization_endpoint: string\n end_session_endpoint: string\n jwks_uri: string\n token_endpoint: string\n userinfo_endpoint: string\n }\n metaLastFetchedTime?: Date\n\n metaPromise?: Promise<void>\n metaPromiseResolve?: () => void\n name: string\n pluginOptions: PluginOptions\n verify: VerifyFunction\n\n constructor(options: Options) {\n this.verify = options.verify\n this.cookieName = options.cookieName\n this.clientID = options.clientID\n this.clientSecret = options.clientSecret\n this.identityMetadataURL = options.identityMetadata\n this.name = options.strategyName\n this.collection = options.collection\n this.collectionOptions = options.collectionOptions\n this.pluginOptions = options.pluginOptions\n this.debug = options.debug || false\n // eslint-disable-next-line no-console, @typescript-eslint/no-explicit-any\n this.debugLog = options.debug ? (...args: any[]) => console.log(...args) : () => null\n // Prevent wokiness with `this`\n this.ensureMeta = this.ensureMeta.bind(this)\n }\n\n async authenticate({\n canSetHeaders,\n headers,\n payload,\n }: AuthStrategyFunctionArgs): Promise<AuthStrategyResult> {\n const debugLogger = createDebugLogger(payload, this.debug)\n await this.ensureMeta()\n\n const cookies = parseCookies(headers)\n\n let oauthToken = cookies.get(this.cookieName)\n const refreshToken = cookies.get(`${this.cookieName}-refresh`)\n\n debugLogger.info({\n msg: 'Retrieved tokens from cookies',\n oauthToken,\n refreshToken,\n })\n\n if (!this.collectionOptions.disableJWTFromHeader) {\n // Parse Authorization header if exists\n const jwtFromHeader = headers.get('authorization')\n if (typeof jwtFromHeader === 'string' && jwtFromHeader.startsWith('Bearer ')) {\n debugLogger.info({\n jwtFromHeader,\n msg: 'Found bearer token in authorization header',\n })\n oauthToken = jwtFromHeader.replace('Bearer ', '')\n }\n }\n\n if (!oauthToken) {\n if (refreshToken && canSetHeaders) {\n debugLogger.info({\n msg: 'No access token found, but refresh token exists. Attempting to refresh...',\n refreshToken,\n })\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n } else {\n return {\n user: null,\n }\n }\n }\n\n let oauthTokenVerifyResult: Error | jwt.JwtPayload | null = null\n\n // First, try to verify token\n if (oauthToken) {\n oauthTokenVerifyResult = await this.jwtVerify({ payload, token: oauthToken })\n\n // If verify comes back null, there is no user\n if (oauthTokenVerifyResult === null) {\n return {\n user: null,\n }\n }\n\n // If verify comes back truthy, use it\n // but first set exp from refresh token\n // because access exp is likely very short lived\n if (\n typeof oauthTokenVerifyResult === 'object' &&\n !(oauthTokenVerifyResult instanceof Error)\n ) {\n if (refreshToken) {\n const refreshTokenExp = getTokenExp({ debugLogger, token: refreshToken })\n\n if (refreshTokenExp) {\n oauthTokenVerifyResult.exp = refreshTokenExp\n }\n }\n\n return this.verify({\n headers,\n payload,\n token: oauthTokenVerifyResult,\n })\n }\n }\n\n if (\n oauthTokenVerifyResult instanceof Error &&\n oauthTokenVerifyResult.name === 'TokenExpiredError' &&\n refreshToken &&\n !this.collectionOptions.usePayloadJWT &&\n canSetHeaders\n ) {\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n\n debugLogger.info({\n msg: 'Token expired. Refreshing...',\n refreshed,\n refreshToken,\n })\n\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n }\n\n return {\n user: null,\n }\n }\n\n async ensureMeta(): Promise<void> {\n if (this.metaPromise) {\n this.debugLog('strategy - metaPromise exists. Waiting for it to resolve...')\n await this.metaPromise\n }\n\n // If no meta or this.metaLastFetchedTime is more than 24 hours old, fetch meta\n if (!this.metaLastFetchedTime || Date.now() - this.metaLastFetchedTime.getTime() > 86_400_000) {\n this.debugLog(\n `Meta is stale. Fetching... Last fetched: ${this.metaLastFetchedTime || 'never'}`,\n )\n await this.fetchMeta()\n }\n }\n\n async fetchMeta(): Promise<void> {\n // If already in-flight, return the existing promise\n if (this.metaPromise) {\n this.debugLog('fetchMeta - returning existing metaPromise')\n return this.metaPromise\n }\n\n this.debugLog('fetchMeta - creating new metaPromise...')\n\n // Build the shared promise\n this.metaPromise = (async () => {\n let lastError: unknown\n\n for (let attempt = 1; attempt <= 5; attempt++) {\n try {\n this.meta = await fetch(this.identityMetadataURL).then((res) => res.json())\n this.debugLog(`fetchMeta - success on attempt ${attempt}`)\n\n if (this.meta?.jwks_uri) {\n this.jwks = await fetch(this.meta.jwks_uri).then((res) => res.json())\n }\n\n this.metaLastFetchedTime = new Date()\n this.debugLog(`fetchMeta - finished at ${this.metaLastFetchedTime.toISOString()}`)\n return\n } catch (error: unknown) {\n lastError = error\n this.debugLog(`fetchMeta - FAILED attempt ${attempt}/5: ${(error as Error)?.message}`)\n\n if (attempt < 5) {\n // Exponential backoff (up to 1s)\n await new Promise((resolve) => setTimeout(resolve, Math.min(attempt * 200, 1000)))\n }\n }\n }\n\n throw new APIError(\n `Failed to fetch identity metadata from \"${this.identityMetadataURL}\". Last error: ${\n (lastError as Error)?.message ?? 'unknown'\n }`,\n )\n })()\n\n try {\n await this.metaPromise\n } finally {\n this.metaPromise = undefined\n }\n }\n\n async generateOidcPEM(kid: string, alg: string): Promise<string> {\n const keys = this && this.jwks && Array.isArray(this.jwks.keys) ? this.jwks.keys : null\n\n let pubKey: null | string = null\n let foundKey = false\n\n if (!kid) {\n throw new Error('kid is missing')\n }\n\n if (!alg) {\n throw new Error('alg is missing')\n }\n\n if (!keys) {\n throw new Error('keys is missing')\n }\n\n for (const key of keys) {\n if (!('kid' in key) || key.kid !== kid) {\n continue\n }\n\n const cryptoKey = await jose.importJWK(key, alg)\n if (!(cryptoKey instanceof CryptoKey)) {\n throw new Error('importJWK did not return a CryptoKey')\n }\n\n pubKey = await jose.exportSPKI(cryptoKey)\n foundKey = true\n\n break\n }\n\n if (!foundKey) {\n throw new Error('a key with the specific kid cannot be found')\n }\n\n if (!pubKey) {\n throw new Error('generating public key pem failed')\n }\n\n return pubKey\n }\n\n async jwtVerify({ payload, token }: JwtVerifyArgs): Promise<Error | jwt.JwtPayload | null> {\n try {\n const verified = await validateProjectToken(token, getEnvironment())\n if (typeof verified !== 'string') {\n return verified\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: 'Error verifying jwt token',\n })\n\n if (err instanceof Error) {\n return err\n }\n return null\n }\n return null\n }\n}\n\ntype JwtVerifyArgs = {\n payload: Payload\n token: string\n}\n"],"names":["jose","APIError","parseCookies","validateProjectToken","getEnvironment","createDebugLogger","getTokenExp","mergeHeaders","refreshTokens","Strategy","clientID","clientSecret","collection","collectionOptions","cookieName","debug","debugLog","identityMetadataURL","jwks","meta","metaLastFetchedTime","metaPromise","metaPromiseResolve","name","pluginOptions","verify","options","identityMetadata","strategyName","args","console","log","ensureMeta","bind","authenticate","canSetHeaders","headers","payload","debugLogger","cookies","oauthToken","get","refreshToken","info","msg","disableJWTFromHeader","jwtFromHeader","startsWith","replace","refreshed","strategy","verifyResult","token","decodedOauthToken","responseHeaders","user","oauthTokenVerifyResult","jwtVerify","Error","refreshTokenExp","exp","usePayloadJWT","Date","now","getTime","fetchMeta","lastError","attempt","fetch","then","res","json","jwks_uri","toISOString","error","message","Promise","resolve","setTimeout","Math","min","undefined","generateOidcPEM","kid","alg","keys","Array","isArray","pubKey","foundKey","key","cryptoKey","importJWK","CryptoKey","exportSPKI","verified","err","logger"],"mappings":"AASA,YAAYA,UAAU,OAAM;AAC5B,SAASC,QAAQ,EAAEC,YAAY,QAAQ,UAAS;AAIhD,SAA6BC,oBAAoB,QAAQ,8BAA6B;AAEtF,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,aAAa,QAAQ,gCAA+B;AAe7D,OAAO,MAAMC;IACXC,SAAgB;IAChBC,aAAqB;IACrBC,WAA4B;IAC5BC,kBAAoC;IACpCC,WAAkB;IAElBC,MAAc;IAEd,8DAA8D;IAC9DC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zF,IAAI;YACF,MAAM2C,WAAW,MAAM5F,qBAAqBiD,OAAOhD;YACnD,IAAI,OAAO2F,aAAa,UAAU;gBAChC,OAAOA;YACT;QACF,EAAE,OAAOC,KAAc;YACrB3D,QAAQ4D,MAAM,CAACvB,KAAK,CAAC;gBACnBsB;gBACApD,KAAK;YACP;YAEA,IAAIoD,eAAetC,OAAO;gBACxB,OAAOsC;YACT;YACA,OAAO;QACT;QACA,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/strategy/index.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\n/* eslint-disable @typescript-eslint/restrict-template-expressions */\nimport type {\n AuthStrategyFunctionArgs,\n AuthStrategyResult,\n CollectionConfig,\n Payload,\n} from 'payload'\n\nimport * as jose from 'jose'\nimport { APIError, parseCookies } from 'payload'\n\nimport type { CollectionOptions, PluginOptions, VerifyFunction } from '../types.js'\n\nimport { JWTValidationError, validateProjectToken } from '../../auth/jwt-validator.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createDebugLogger } from '../utilities/createDebugLogger.js'\nimport { getTokenExp } from '../utilities/getTokenExp.js'\nimport { mergeHeaders } from '../utilities/mergeHeaders.js'\nimport { refreshTokens } from '../utilities/refreshTokens.js'\n\nexport interface Options {\n clientID: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n debug?: boolean\n identityMetadata: string\n pluginOptions: PluginOptions\n strategyName: string\n verify: VerifyFunction\n}\n\nexport class Strategy {\n clientID: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n\n debug: boolean\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n debugLog: (...args: any[]) => void\n\n identityMetadataURL: string\n jwks?: {\n keys: jose.JWK[]\n }\n meta?: {\n authorization_endpoint: string\n end_session_endpoint: string\n jwks_uri: string\n token_endpoint: string\n userinfo_endpoint: string\n }\n metaLastFetchedTime?: Date\n\n metaPromise?: Promise<void>\n metaPromiseResolve?: () => void\n name: string\n pluginOptions: PluginOptions\n verify: VerifyFunction\n\n constructor(options: Options) {\n this.verify = options.verify\n this.cookieName = options.cookieName\n this.clientID = options.clientID\n this.identityMetadataURL = options.identityMetadata\n this.name = options.strategyName\n this.collection = options.collection\n this.collectionOptions = options.collectionOptions\n this.pluginOptions = options.pluginOptions\n this.debug = options.debug || false\n // eslint-disable-next-line no-console, @typescript-eslint/no-explicit-any\n this.debugLog = options.debug ? (...args: any[]) => console.log(...args) : () => null\n // Prevent wokiness with `this`\n this.ensureMeta = this.ensureMeta.bind(this)\n }\n\n async authenticate({\n canSetHeaders,\n headers,\n payload,\n }: AuthStrategyFunctionArgs): Promise<AuthStrategyResult> {\n const debugLogger = createDebugLogger(payload, this.debug)\n await this.ensureMeta()\n\n const cookies = parseCookies(headers)\n\n let oauthToken = cookies.get(this.cookieName)\n const refreshToken = cookies.get(`${this.cookieName}-refresh`)\n\n debugLogger.info({\n msg: 'Retrieved tokens from cookies',\n oauthToken,\n refreshToken,\n })\n\n if (!this.collectionOptions.disableJWTFromHeader) {\n // Parse Authorization header if exists\n const jwtFromHeader = headers.get('authorization')\n if (typeof jwtFromHeader === 'string' && jwtFromHeader.startsWith('Bearer ')) {\n debugLogger.info({\n jwtFromHeader,\n msg: 'Found bearer token in authorization header',\n })\n oauthToken = jwtFromHeader.replace('Bearer ', '')\n }\n }\n\n if (!oauthToken) {\n // Attempt refresh even when canSetHeaders=false (e.g., during RSC navigation).\n // This allows authentication to succeed for the current request even when\n // cookies cannot be updated. The cookie will be refreshed on the next\n // full page load when canSetHeaders=true.\n if (refreshToken) {\n debugLogger.info({\n msg: 'No access token found, but refresh token exists. Attempting to refresh...',\n refreshToken,\n })\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n // Only return response headers (to set cookies) when canSetHeaders is true.\n // During RSC navigation, canSetHeaders=false because response streaming\n // has already started and cookies cannot be modified.\n if (canSetHeaders) {\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n }\n\n // Authenticate this request without updating cookies\n return {\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n }\n\n return {\n user: null,\n }\n }\n\n let oauthTokenVerifyResult: Error | jwt.JwtPayload | null = null\n\n // First, try to verify token\n if (oauthToken) {\n oauthTokenVerifyResult = await this.jwtVerify({ payload, token: oauthToken })\n\n // If verify comes back null, there is no user\n if (oauthTokenVerifyResult === null) {\n return {\n user: null,\n }\n }\n\n // If verify comes back truthy, use it\n // but first set exp from refresh token\n // because access exp is likely very short lived\n if (\n typeof oauthTokenVerifyResult === 'object' &&\n !(oauthTokenVerifyResult instanceof Error)\n ) {\n if (refreshToken) {\n const refreshTokenExp = getTokenExp({ debugLogger, token: refreshToken })\n\n if (refreshTokenExp) {\n oauthTokenVerifyResult.exp = refreshTokenExp\n }\n }\n\n return this.verify({\n headers,\n payload,\n token: oauthTokenVerifyResult,\n })\n }\n }\n\n // Handle expired access token with valid refresh token.\n // Same pattern as above: refresh regardless of canSetHeaders to support RSC navigation,\n // but only update cookies when canSetHeaders=true.\n if (\n oauthTokenVerifyResult instanceof JWTValidationError &&\n oauthTokenVerifyResult.code === 'EXPIRED' &&\n refreshToken &&\n !this.collectionOptions.usePayloadJWT\n ) {\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n\n debugLogger.info({\n msg: 'Token expired. Refreshing...',\n refreshed,\n refreshToken,\n })\n\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n if (canSetHeaders) {\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n }\n\n // Authenticate this request without updating cookies\n return {\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n }\n\n return {\n user: null,\n }\n }\n\n async ensureMeta(): Promise<void> {\n if (this.metaPromise) {\n this.debugLog('strategy - metaPromise exists. Waiting for it to resolve...')\n await this.metaPromise\n }\n\n // If no meta or this.metaLastFetchedTime is more than 24 hours old, fetch meta\n if (!this.metaLastFetchedTime || Date.now() - this.metaLastFetchedTime.getTime() > 86_400_000) {\n this.debugLog(\n `Meta is stale. Fetching... Last fetched: ${this.metaLastFetchedTime || 'never'}`,\n )\n await this.fetchMeta()\n }\n }\n\n async fetchMeta(): Promise<void> {\n // If already in-flight, return the existing promise\n if (this.metaPromise) {\n this.debugLog('fetchMeta - returning existing metaPromise')\n return this.metaPromise\n }\n\n this.debugLog('fetchMeta - creating new metaPromise...')\n\n // Build the shared promise\n this.metaPromise = (async () => {\n let lastError: unknown\n\n for (let attempt = 1; attempt <= 5; attempt++) {\n try {\n this.meta = await fetch(this.identityMetadataURL).then((res) => res.json())\n\n if (this.meta) {\n // TODO: This is a hack to get the DefaultLoginButton to work with dynamic OAuth client registration\n this.meta.authorization_endpoint = this.meta?.authorization_endpoint + '/cms'\n }\n\n this.debugLog(`fetchMeta - success on attempt ${attempt}`)\n\n if (this.meta?.jwks_uri) {\n this.jwks = await fetch(this.meta.jwks_uri).then((res) => res.json())\n }\n\n this.metaLastFetchedTime = new Date()\n this.debugLog(`fetchMeta - finished at ${this.metaLastFetchedTime.toISOString()}`)\n return\n } catch (error: unknown) {\n lastError = error\n this.debugLog(`fetchMeta - FAILED attempt ${attempt}/5: ${(error as Error)?.message}`)\n\n if (attempt < 5) {\n // Exponential backoff (up to 1s)\n await new Promise((resolve) => setTimeout(resolve, Math.min(attempt * 200, 1000)))\n }\n }\n }\n\n throw new APIError(\n `Failed to fetch identity metadata from \"${this.identityMetadataURL}\". Last error: ${\n (lastError as Error)?.message ?? 'unknown'\n }`,\n )\n })()\n\n try {\n await this.metaPromise\n } finally {\n this.metaPromise = undefined\n }\n }\n\n async generateOidcPEM(kid: string, alg: string): Promise<string> {\n const keys = this && this.jwks && Array.isArray(this.jwks.keys) ? this.jwks.keys : null\n\n let pubKey: null | string = null\n let foundKey = false\n\n if (!kid) {\n throw new Error('kid is missing')\n }\n\n if (!alg) {\n throw new Error('alg is missing')\n }\n\n if (!keys) {\n throw new Error('keys is missing')\n }\n\n for (const key of keys) {\n if (!('kid' in key) || key.kid !== kid) {\n continue\n }\n\n const cryptoKey = await jose.importJWK(key, alg)\n if (!(cryptoKey instanceof CryptoKey)) {\n throw new Error('importJWK did not return a CryptoKey')\n }\n\n pubKey = await jose.exportSPKI(cryptoKey)\n foundKey = true\n\n break\n }\n\n if (!foundKey) {\n throw new Error('a key with the specific kid cannot be found')\n }\n\n if (!pubKey) {\n throw new Error('generating public key pem failed')\n }\n\n return pubKey\n }\n\n async jwtVerify({ payload, token }: JwtVerifyArgs): Promise<Error | jwt.JwtPayload | null> {\n try {\n const verified = await validateProjectToken(token, getEnvironment())\n if (typeof verified !== 'string') {\n return verified\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: 'Error verifying jwt token',\n })\n\n if (err instanceof Error) {\n return err\n }\n return null\n }\n return null\n }\n}\n\ntype JwtVerifyArgs = {\n payload: Payload\n token: string\n}\n"],"names":["jose","APIError","parseCookies","JWTValidationError","validateProjectToken","getEnvironment","createDebugLogger","getTokenExp","mergeHeaders","refreshTokens","Strategy","clientID","collection","collectionOptions","cookieName","debug","debugLog","identityMetadataURL","jwks","meta","metaLastFetchedTime","metaPromise","metaPromiseResolve","name","pluginOptions","verify","options","identityMetadata","strategyName","args","console","log","ensureMeta","bind","authenticate","canSetHeaders","headers","payload","debugLogger","cookies","oauthToken","get","refreshToken","info","msg","disableJWTFromHeader","jwtFromHeader","startsWith","replace","refreshed","strategy","verifyResult","token","decodedOauthToken","responseHeaders","user","oauthTokenVerifyResult","jwtVerify","Error","refreshTokenExp","exp","code","usePayloadJWT","Date","now","getTime","fetchMeta","lastError","attempt","fetch","then","res","json","authorization_endpoint","jwks_uri","toISOString","error","message","Promise","resolve","setTimeout","Math","min","undefined","generateOidcPEM","kid","alg","keys","Array","isArray","pubKey","foundKey","key","cryptoKey","importJWK","CryptoKey","exportSPKI","verified","err","logger"],"mappings":"AASA,YAAYA,UAAU,OAAM;AAC5B,SAASC,QAAQ,EAAEC,YAAY,QAAQ,UAAS;AAIhD,SAASC,kBAAkB,EAAEC,oBAAoB,QAAQ,8BAA6B;AACtF,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,aAAa,QAAQ,gCAA+B;AAc7D,OAAO,MAAMC;IACXC,SAAgB;IAChBC,WAA4B;IAC5BC,kBAAoC;IACpCC,WAAkB;IAElBC,MAAc;IAEd,8DAA8D;IAC9DC,SAAkC;IAElCC,oBAA2B;IAC3BC,KAEC;IACDC,KAMC;IACDC,oBAA0B;IAE1BC,YAA2B;IAC3BC,mBAA+B;IAC/BC,KAAY;IACZC,cAA4B;IAC5BC,OAAsB;IAEtB,YAAYC,OAAgB,CAAE;QAC5B,IAAI,CAACD,MAAM,GAAGC,QAAQD,MAAM;QAC5B,IAAI,CAACX,UAAU,GAAGY,QAAQZ,UAAU;QACpC,IAAI,CAACH,QAAQ,GAAGe,QAAQf,QAAQ;QAChC,IAAI,CAACM,mBAAmB,GAAGS,QAAQC,gBAAgB;QACnD,IAAI,CAACJ,IAAI,GAAGG,QAAQE,YAAY;QAChC,IAAI,CAAChB,UAAU,GAAGc,QAAQd,UAAU;QACpC,IAAI,CAACC,iBAAiB,GAAGa,QAAQb,iBAAi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BAChC,OAAOA;YACT;QACF,EAAE,OAAOC,KAAc;YACrB7D,QAAQ8D,MAAM,CAACvB,KAAK,CAAC;gBACnBsB;gBACAtD,KAAK;YACP;YAEA,IAAIsD,eAAexC,OAAO;gBACxB,OAAOwC;YACT;YACA,OAAO;QACT;QACA,OAAO;IACT;AACF"}
|
package/dist/oauth/types.d.ts
CHANGED
|
@@ -30,7 +30,7 @@ export interface CollectionOptions {
|
|
|
30
30
|
* Set to false to only accept the JWT from cookies
|
|
31
31
|
*/
|
|
32
32
|
disableJWTFromHeader?: boolean;
|
|
33
|
-
disableLocalStrategy?:
|
|
33
|
+
disableLocalStrategy?: false | IncomingAuthType['disableLocalStrategy'];
|
|
34
34
|
/**
|
|
35
35
|
* The logout button will either redirect to the IDP logout screen or
|
|
36
36
|
* automatically log the user out of the IDP depending on provider.
|
|
@@ -112,11 +112,6 @@ export interface PluginOptions {
|
|
|
112
112
|
* @default 'payload-oauth-token'
|
|
113
113
|
*/
|
|
114
114
|
cookieName?: string;
|
|
115
|
-
/**
|
|
116
|
-
* Debug mode will log additional information to the console.
|
|
117
|
-
*
|
|
118
|
-
* NOTE: This will log sensitive information to the console.
|
|
119
|
-
*/
|
|
120
115
|
/**
|
|
121
116
|
* Accepts incoming request and allows for modification of cookie options
|
|
122
117
|
*/
|
|
@@ -125,6 +120,11 @@ export interface PluginOptions {
|
|
|
125
120
|
cookieOptions: CookieOptions;
|
|
126
121
|
headers: Headers;
|
|
127
122
|
}) => CookieOptions;
|
|
123
|
+
/**
|
|
124
|
+
* Debug mode will log additional information to the console.
|
|
125
|
+
*
|
|
126
|
+
* NOTE: This will log sensitive information to the console.
|
|
127
|
+
*/
|
|
128
128
|
debug?: boolean;
|
|
129
129
|
/**
|
|
130
130
|
* Disables the plugin functionality while leaving in types, fields and component modifications.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/oauth/types.ts"],"names":[],"mappings":"AACA,OAAO,KA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,CAAC,EAAE,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAA;IACpC,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB,CAAA;AAED,MAAM,MAAM,QAAQ,GAAG;IACrB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;OAEG;IACH,GAAG,EAAE,MAAM,CAAA;IACX;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,MAAM,MAAM,KAAK,GAAG;IAClB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA;IACnC,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA;IAClD,CAAC,CAAC,SAAS,MAAM,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI,CAAA;CAC/D,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,KAAK,CAAA;IACZ,IAAI,EAAE,KAAK,CAAA;CACZ,CAAA"}
|
package/dist/oauth/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/oauth/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type jwt from 'jsonwebtoken'\nimport type {\n AuthStrategyResult,\n CollectionConfig,\n CustomComponent,\n EmailField,\n IncomingAuthType,\n Payload,\n PayloadRequest,\n TextField,\n} from 'payload'\n\nexport type Done = (error: any, user?: any, info?: unknown) => void\n\nexport type VerifyFunction = (args: {\n headers: Headers\n payload: Payload\n token: jwt.JwtPayload\n}) => Promise<AuthStrategyResult>\n\nexport type AfterOAuthLoginHookResult = {\n redirect?: string\n} | void\n\nexport type AfterOAuthLoginHook = (args: {\n access_token?: string\n id_token?: string\n refresh_token?: string\n req: PayloadRequest\n}) => AfterOAuthLoginHookResult | Promise<AfterOAuthLoginHookResult>\n\nexport interface CollectionOptions {\n authorizationURLParams?: Record<string, string>\n\n clientID: string\n clientSecret?: string\n\n /**\n * Whether to disable the local strategy for this collection.\n *\n * @default true\n */\n\n /**\n * By default, accept a JWT from the authorization header\n *\n * Set to false to only accept the JWT from cookies\n */\n disableJWTFromHeader?: boolean\n\n disableLocalStrategy?:
|
|
1
|
+
{"version":3,"sources":["../../src/oauth/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type jwt from 'jsonwebtoken'\nimport type {\n AuthStrategyResult,\n CollectionConfig,\n CustomComponent,\n EmailField,\n IncomingAuthType,\n Payload,\n PayloadRequest,\n TextField,\n} from 'payload'\n\nexport type Done = (error: any, user?: any, info?: unknown) => void\n\nexport type VerifyFunction = (args: {\n headers: Headers\n payload: Payload\n token: jwt.JwtPayload\n}) => Promise<AuthStrategyResult>\n\nexport type AfterOAuthLoginHookResult = {\n redirect?: string\n} | void\n\nexport type AfterOAuthLoginHook = (args: {\n access_token?: string\n id_token?: string\n refresh_token?: string\n req: PayloadRequest\n}) => AfterOAuthLoginHookResult | Promise<AfterOAuthLoginHookResult>\n\nexport interface CollectionOptions {\n authorizationURLParams?: Record<string, string>\n\n clientID: string\n clientSecret?: string\n\n /**\n * Whether to disable the local strategy for this collection.\n *\n * @default true\n */\n\n /**\n * By default, accept a JWT from the authorization header\n *\n * Set to false to only accept the JWT from cookies\n */\n disableJWTFromHeader?: boolean\n\n disableLocalStrategy?: false | IncomingAuthType['disableLocalStrategy']\n /**\n * The logout button will either redirect to the IDP logout screen or\n * automatically log the user out of the IDP depending on provider.\n *\n * @default false\n */\n endOAuthSessionOnLogout?: boolean\n hooks?: {\n afterLogin?: AfterOAuthLoginHook[]\n }\n /**\n * The OpenID metadata endpoint for the identity provider.\n *\n * @example http://localhost:8080/realms/master/.well-known/openid-configuration\n * @example https://myapp.auth0.com/.well-known/openid-configuration\n */\n identityMetadata: string\n /**\n * Custom React component to use as the login button on the login page.\n */\n LoginButton?: CustomComponent | false\n /**\n * The OAuth2.0 scope to request from the identity provider.\n *\n * @default ['openid', 'profile', 'email']\n */\n scope?: string[]\n /**\n * The Payload collection slug to apply the OAuth2.0 strategy to.\n */\n slug: string\n /**\n * Property to use as the token to decode from the OAuth2.0 response.\n *\n * This is passed to the default or custom `verify` function.\n *\n * @default 'access_token'\n */\n token?: 'access_token' | 'id_token'\n\n /**\n * Have Payload maintain the JWT cookie.\n *\n * This is for when the IDP does not support silently refreshing tokens in the background.\n */\n usePayloadJWT?: boolean\n\n /**\n * The Payload field to use as the username field for the user\n * When a text is used, the plugin will find the collection field with the name provided\n * Alternatively define the entire field to use\n * @default\n *\n * ```ts\n * {\n * type: 'text',\n * name: 'preferredUsername',\n * unique: true,\n * admin: {\n * position: 'sidebar',\n * readOnly: true,\n * },\n * }\n * ```\n */\n usernameField?: EmailField | string | TextField\n\n /**\n * Custom verify function that receives the token and performs any logic.\n * By default, the defaultVerify function is used.\n */\n verify?: VerifyFunction\n}\n\nexport interface PluginOptions {\n /**\n * The collections to apply the OAuth2.0 strategy to.\n */\n collections: CollectionOptions[]\n /**\n * The name of the cookie to use for storing the user's token.\n *\n * @default 'payload-oauth-token'\n */\n cookieName?: string\n /**\n * Accepts incoming request and allows for modification of cookie options\n */\n createCookieOptions?: (args: {\n collection: CollectionConfig\n cookieOptions: CookieOptions\n headers: Headers\n }) => CookieOptions\n\n /**\n * Debug mode will log additional information to the console.\n *\n * NOTE: This will log sensitive information to the console.\n */\n debug?: boolean\n /**\n * Disables the plugin functionality while leaving in types, fields and component modifications.\n * @default false\n */\n disabled?: boolean\n /**\n * OAuth2.0 requires a URL to redirect the user to.\n * If you do not have a `config.serverURL` defined in your Payload config, you must define this string to be set as where the identity provider should redirect users once logged in.\n */\n redirectServerURL?: string\n /**\n * Override the strategy name used for this plugin.\n *\n * This should only be overridden to accomodate multiple plugin\n * invocations against a single user collection.\n *\n * If you have a custom basePath defined in your Next config,\n * this value should not contain that path.\n *\n * @default 'oauth'\n */\n strategyName?: string\n}\n\nexport type CookieOptions = {\n domain?: string\n expires?: Date | number\n httpOnly?: boolean\n maxAge?: number\n path?: string\n sameSite?: 'Lax' | 'None' | 'Strict'\n secure?: boolean\n}\n\nexport type StateObj = {\n /**\n * Redirect to use if the login fails\n */\n failedRedirect?: string\n /**\n * Redirect to use after the login is successful\n */\n redirect?: string\n /**\n * The URL that will be used for Payload to redirect to\n */\n serverURL?: string\n /**\n * Encrypted signature to be verified\n */\n sig: string\n /**\n * Code verifier used for PKCE\n */\n verifier: string\n}\n\nexport type LogFn = {\n (msg: string, ...args: any[]): void\n (obj: unknown, msg?: string, ...args: any[]): void\n <T extends object>(obj: T, msg?: string, ...args: any[]): void\n}\n\nexport type DebugLogger = {\n error: LogFn\n info: LogFn\n}\n"],"names":[],"mappings":"AAAA,qDAAqD,GAuNrD,WAGC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCookieOptions.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"createCookieOptions.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE/D,UAAU,IAAI;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,OAAO,EAAE,OAAO,CAAA;IAChB,aAAa,EAAE,aAAa,CAAA;CAC7B;AAED,eAAO,MAAM,mBAAmB,4CAI7B,IAAI,KAAG,aA8CT,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"sourcesContent":["import type { CollectionConfig
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { CookieOptions, PluginOptions } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n headers: Headers\n pluginOptions: PluginOptions\n}\n\nexport const createCookieOptions = ({\n collection,\n headers,\n pluginOptions,\n}: Args): CookieOptions => {\n let cookieOptions: CookieOptions = {\n domain: undefined,\n httpOnly: true,\n path: '/',\n sameSite: undefined,\n secure: false,\n }\n\n if (typeof collection.auth === 'object' && typeof collection.auth.cookies === 'object') {\n const { domain, sameSite, secure } = collection.auth.cookies\n if (typeof secure === 'boolean') {\n cookieOptions.secure = secure\n }\n if (typeof sameSite === 'string') {\n cookieOptions.sameSite = sameSite as 'Lax'\n }\n if (typeof domain === 'string') {\n cookieOptions.domain = domain\n }\n }\n\n if (typeof collection.auth === 'object' && typeof collection.auth.cookies === 'object') {\n if (collection.auth.cookies.secure) {\n cookieOptions.secure = true\n }\n if (collection.auth.cookies.sameSite) {\n cookieOptions.sameSite =\n typeof collection.auth.cookies.sameSite === 'string'\n ? collection.auth.cookies.sameSite\n : 'Lax'\n }\n if (collection.auth.cookies.domain) {\n cookieOptions.domain = collection.auth.cookies.domain\n }\n }\n\n if (typeof pluginOptions.createCookieOptions === 'function') {\n cookieOptions = pluginOptions.createCookieOptions({\n collection,\n cookieOptions,\n headers,\n })\n }\n\n return cookieOptions\n}\n"],"names":["createCookieOptions","collection","headers","pluginOptions","cookieOptions","domain","undefined","httpOnly","path","sameSite","secure","auth","cookies"],"mappings":"AAUA,OAAO,MAAMA,sBAAsB,CAAC,EAClCC,UAAU,EACVC,OAAO,EACPC,aAAa,EACR;IACL,IAAIC,gBAA+B;QACjCC,QAAQC;QACRC,UAAU;QACVC,MAAM;QACNC,UAAUH;QACVI,QAAQ;IACV;IAEA,IAAI,OAAOT,WAAWU,IAAI,KAAK,YAAY,OAAOV,WAAWU,IAAI,CAACC,OAAO,KAAK,UAAU;QACtF,MAAM,EAAEP,MAAM,EAAEI,QAAQ,EAAEC,MAAM,EAAE,GAAGT,WAAWU,IAAI,CAACC,OAAO;QAC5D,IAAI,OAAOF,WAAW,WAAW;YAC/BN,cAAcM,MAAM,GAAGA;QACzB;QACA,IAAI,OAAOD,aAAa,UAAU;YAChCL,cAAcK,QAAQ,GAAGA;QAC3B;QACA,IAAI,OAAOJ,WAAW,UAAU;YAC9BD,cAAcC,MAAM,GAAGA;QACzB;IACF;IAEA,IAAI,OAAOJ,WAAWU,IAAI,KAAK,YAAY,OAAOV,WAAWU,IAAI,CAACC,OAAO,KAAK,UAAU;QACtF,IAAIX,WAAWU,IAAI,CAACC,OAAO,CAACF,MAAM,EAAE;YAClCN,cAAcM,MAAM,GAAG;QACzB;QACA,IAAIT,WAAWU,IAAI,CAACC,OAAO,CAACH,QAAQ,EAAE;YACpCL,cAAcK,QAAQ,GACpB,OAAOR,WAAWU,IAAI,CAACC,OAAO,CAACH,QAAQ,KAAK,WACxCR,WAAWU,IAAI,CAACC,OAAO,CAACH,QAAQ,GAChC;QACR;QACA,IAAIR,WAAWU,IAAI,CAACC,OAAO,CAACP,MAAM,EAAE;YAClCD,cAAcC,MAAM,GAAGJ,WAAWU,IAAI,CAACC,OAAO,CAACP,MAAM;QACvD;IACF;IAEA,IAAI,OAAOF,cAAcH,mBAAmB,KAAK,YAAY;QAC3DI,gBAAgBD,cAAcH,mBAAmB,CAAC;YAChDC;YACAG;YACAF;QACF;IACF;IAEA,OAAOE;AACT,EAAC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Check if an error is a duplicate key/unique constraint violation from Content API.
|
|
3
|
+
*
|
|
4
|
+
* Content API returns HTTP 409 with "conflict" or "already exists" in the message.
|
|
5
|
+
*/
|
|
6
|
+
export declare function isDuplicateKeyError(error: unknown): boolean;
|
|
7
|
+
//# sourceMappingURL=isDuplicateKeyError.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isDuplicateKeyError.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/isDuplicateKeyError.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAa3D"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Check if an error is a duplicate key/unique constraint violation from Content API.
|
|
3
|
+
*
|
|
4
|
+
* Content API returns HTTP 409 with "conflict" or "already exists" in the message.
|
|
5
|
+
*/ export function isDuplicateKeyError(error) {
|
|
6
|
+
if (!error || typeof error !== 'object') {
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
const err = error;
|
|
10
|
+
const message = typeof err.message === 'string' ? err.message : '';
|
|
11
|
+
return message.includes('409') || message.toLowerCase().includes('conflict') || message.toLowerCase().includes('already exists');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=isDuplicateKeyError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/utilities/isDuplicateKeyError.ts"],"sourcesContent":["/**\n * Check if an error is a duplicate key/unique constraint violation from Content API.\n *\n * Content API returns HTTP 409 with \"conflict\" or \"already exists\" in the message.\n */\nexport function isDuplicateKeyError(error: unknown): boolean {\n if (!error || typeof error !== 'object') {\n return false\n }\n\n const err = error as { message?: unknown }\n const message = typeof err.message === 'string' ? err.message : ''\n\n return (\n message.includes('409') ||\n message.toLowerCase().includes('conflict') ||\n message.toLowerCase().includes('already exists')\n )\n}\n"],"names":["isDuplicateKeyError","error","err","message","includes","toLowerCase"],"mappings":"AAAA;;;;CAIC,GACD,OAAO,SAASA,oBAAoBC,KAAc;IAChD,IAAI,CAACA,SAAS,OAAOA,UAAU,UAAU;QACvC,OAAO;IACT;IAEA,MAAMC,MAAMD;IACZ,MAAME,UAAU,OAAOD,IAAIC,OAAO,KAAK,WAAWD,IAAIC,OAAO,GAAG;IAEhE,OACEA,QAAQC,QAAQ,CAAC,UACjBD,QAAQE,WAAW,GAAGD,QAAQ,CAAC,eAC/BD,QAAQE,WAAW,GAAGD,QAAQ,CAAC;AAEnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refreshTokens.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/refreshTokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAItC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"refreshTokens.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/refreshTokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAItC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AASpD,UAAU,IAAI;IACZ,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,EAAE,MAAM,CAAA;IACpB,QAAQ,EAAE,QAAQ,CAAA;CACnB;AAED,KAAK,MAAM,GACP;IACE,iBAAiB,EAAE,GAAG,CAAC,UAAU,CAAA;IACjC,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;CACd,GACD,KAAK,CAAA;AAET,eAAO,MAAM,aAAa,wCAA+C,IAAI,KAAG,OAAO,CAAC,MAAM,CAsE7F,CAAA"}
|
|
@@ -16,7 +16,7 @@ export const refreshTokens = async ({ payload, refreshToken, strategy })=>{
|
|
|
16
16
|
// so we will refresh both tokens
|
|
17
17
|
try {
|
|
18
18
|
// Get another project token
|
|
19
|
-
const { expiresAt, token } = await getProjectToken(refreshToken,
|
|
19
|
+
const { expiresAt, token } = await getProjectToken(refreshToken, payload.config.custom.figma.contentSystemId);
|
|
20
20
|
debugLogger.info({
|
|
21
21
|
expiresAt,
|
|
22
22
|
msg: 'Received new tokens from Figma API',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/utilities/refreshTokens.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\nimport type { Payload } from 'payload'\n\nimport { generateCookie } from 'payload'\n\nimport type { Strategy } from '../strategy/index.js'\n\nimport { getProjectToken } from '../../api/figma-api.js'\nimport { validateProjectToken } from '../../auth/jwt-validator.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createCookieOptions } from './createCookieOptions.js'\nimport { createDebugLogger } from './createDebugLogger.js'\nimport { getCookieExpiration } from './getCookieExpiration.js'\
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/utilities/refreshTokens.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\nimport type { Payload } from 'payload'\n\nimport { generateCookie } from 'payload'\n\nimport type { Strategy } from '../strategy/index.js'\n\nimport { getProjectToken } from '../../api/figma-api.js'\nimport { validateProjectToken } from '../../auth/jwt-validator.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createCookieOptions } from './createCookieOptions.js'\nimport { createDebugLogger } from './createDebugLogger.js'\nimport { getCookieExpiration } from './getCookieExpiration.js'\n\ninterface Args {\n payload: Payload\n refreshToken: string\n strategy: Strategy\n}\n\ntype Result =\n | {\n decodedOauthToken: jwt.JwtPayload\n headers: Headers\n token: string\n }\n | false\n\nexport const refreshTokens = async ({ payload, refreshToken, strategy }: Args): Promise<Result> => {\n const debugLogger = createDebugLogger(payload, strategy.debug)\n\n debugLogger.info({\n msg: 'Refreshing tokens',\n })\n\n const headers = new Headers()\n\n // At this point, access token is expired\n // but refresh token is still valid\n // so we will refresh both tokens\n\n try {\n // Get another project token\n const { expiresAt, token } = await getProjectToken(\n refreshToken,\n payload.config.custom.figma.contentSystemId,\n )\n\n debugLogger.info({\n expiresAt,\n msg: 'Received new tokens from Figma API',\n token,\n })\n\n // On error, no user\n if (!token) {\n debugLogger.error({\n msg: 'Error refreshing tokens',\n })\n return false\n }\n\n if (token) {\n debugLogger.info({\n msg: 'Successfully refreshed project token',\n token,\n })\n\n const expires_in = new Date(expiresAt)\n\n const cookieOptions = createCookieOptions({\n collection: strategy.collection,\n headers,\n pluginOptions: strategy.pluginOptions,\n })\n\n const tokenCookie = generateCookie({\n ...cookieOptions,\n name: strategy.cookieName,\n expires: getCookieExpiration(expires_in),\n returnCookieAsObject: false,\n value: token,\n }) as string\n\n headers.append('Set-Cookie', tokenCookie)\n\n const decodedOauthToken = await validateProjectToken(token, getEnvironment())\n\n return { decodedOauthToken, headers, token }\n }\n } catch (error) {\n debugLogger.error({\n err: error,\n msg: 'Error refreshing tokens',\n })\n }\n\n return false\n}\n"],"names":["generateCookie","getProjectToken","validateProjectToken","getEnvironment","createCookieOptions","createDebugLogger","getCookieExpiration","refreshTokens","payload","refreshToken","strategy","debugLogger","debug","info","msg","headers","Headers","expiresAt","token","config","custom","figma","contentSystemId","error","expires_in","Date","cookieOptions","collection","pluginOptions","tokenCookie","name","cookieName","expires","returnCookieAsObject","value","append","decodedOauthToken","err"],"mappings":"AAGA,SAASA,cAAc,QAAQ,UAAS;AAIxC,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,mBAAmB,QAAQ,2BAA0B;AAgB9D,OAAO,MAAMC,gBAAgB,OAAO,EAAEC,OAAO,EAAEC,YAAY,EAAEC,QAAQ,EAAQ;IAC3E,MAAMC,cAAcN,kBAAkBG,SAASE,SAASE,KAAK;IAE7DD,YAAYE,IAAI,CAAC;QACfC,KAAK;IACP;IAEA,MAAMC,UAAU,IAAIC;IAEpB,yCAAyC;IACzC,mCAAmC;IACnC,iCAAiC;IAEjC,IAAI;QACF,4BAA4B;QAC5B,MAAM,EAAEC,SAAS,EAAEC,KAAK,EAAE,GAAG,MAAMjB,gBACjCQ,cACAD,QAAQW,MAAM,CAACC,MAAM,CAACC,KAAK,CAACC,eAAe;QAG7CX,YAAYE,IAAI,CAAC;YACfI;YACAH,KAAK;YACLI;QACF;QAEA,oBAAoB;QACpB,IAAI,CAACA,OAAO;YACVP,YAAYY,KAAK,CAAC;gBAChBT,KAAK;YACP;YACA,OAAO;QACT;QAEA,IAAII,OAAO;YACTP,YAAYE,IAAI,CAAC;gBACfC,KAAK;gBACLI;YACF;YAEA,MAAMM,aAAa,IAAIC,KAAKR;YAE5B,MAAMS,gBAAgBtB,oBAAoB;gBACxCuB,YAAYjB,SAASiB,UAAU;gBAC/BZ;gBACAa,eAAelB,SAASkB,aAAa;YACvC;YAEA,MAAMC,cAAc7B,eAAe;gBACjC,GAAG0B,aAAa;gBAChBI,MAAMpB,SAASqB,UAAU;gBACzBC,SAAS1B,oBAAoBkB;gBAC7BS,sBAAsB;gBACtBC,OAAOhB;YACT;YAEAH,QAAQoB,MAAM,CAAC,cAAcN;YAE7B,MAAMO,oBAAoB,MAAMlC,qBAAqBgB,OAAOf;YAE5D,OAAO;gBAAEiC;gBAAmBrB;gBAASG;YAAM;QAC7C;IACF,EAAE,OAAOK,OAAO;QACdZ,YAAYY,KAAK,CAAC;YAChBc,KAAKd;YACLT,KAAK;QACP;IACF;IAEA,OAAO;AACT,EAAC"}
|
|
@@ -10,25 +10,42 @@ import type { Config, SanitizedConfig } from 'payload';
|
|
|
10
10
|
* @example
|
|
11
11
|
* // Minimal config
|
|
12
12
|
* const config: FigmaConfig = {
|
|
13
|
+
* figma: {
|
|
14
|
+
* contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!
|
|
15
|
+
* },
|
|
13
16
|
* collections: [...]
|
|
14
17
|
* }
|
|
15
18
|
*
|
|
16
19
|
* @example
|
|
17
20
|
* // With custom editor
|
|
18
21
|
* const config: FigmaConfig = {
|
|
22
|
+
* figma: {
|
|
23
|
+
* contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!
|
|
24
|
+
* },
|
|
19
25
|
* collections: [...],
|
|
20
26
|
* editor: lexicalEditor({ features: [...] })
|
|
21
27
|
* }
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* // Disable Content System (use custom db)
|
|
31
|
+
* const config: FigmaConfig = {
|
|
32
|
+
* figma: {
|
|
33
|
+
* contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,
|
|
34
|
+
* useContentSystem: false
|
|
35
|
+
* },
|
|
36
|
+
* db: mongooseAdapter({ url: process.env.DATABASE_URI }),
|
|
37
|
+
* collections: [...]
|
|
38
|
+
* }
|
|
22
39
|
*/
|
|
23
40
|
export type FigmaConfig = {
|
|
24
41
|
editor?: Config['editor'];
|
|
25
42
|
} & {
|
|
26
43
|
figma: {
|
|
27
|
-
|
|
28
|
-
|
|
44
|
+
contentSystemId: string;
|
|
45
|
+
storage?: boolean;
|
|
29
46
|
useContentSystem?: boolean;
|
|
30
47
|
};
|
|
31
|
-
} & Omit<Config, '
|
|
48
|
+
} & Omit<Config, 'db' | 'editor' | 'secret'> & Partial<Pick<Config, 'db'>>;
|
|
32
49
|
/**
|
|
33
50
|
* Figma platform wrapper for Payload's buildConfig.
|
|
34
51
|
* Automatically injects:
|
|
@@ -39,5 +56,5 @@ export type FigmaConfig = {
|
|
|
39
56
|
* @param config - Payload configuration (db and secret omitted, editor optional)
|
|
40
57
|
* @returns Promise<SanitizedConfig> - Built Payload configuration
|
|
41
58
|
*/
|
|
42
|
-
export declare function
|
|
59
|
+
export declare function buildFigmaConfig(config: FigmaConfig): Promise<SanitizedConfig>;
|
|
43
60
|
//# sourceMappingURL=build-config.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-config.d.ts","sourceRoot":"","sources":["../../src/plugin/build-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"build-config.d.ts","sourceRoot":"","sources":["../../src/plugin/build-config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAkBtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAA;CAC1B,GAAG;IACF,KAAK,EAAE;QACL,eAAe,EAAE,MAAM,CAAA;QACvB,OAAO,CAAC,EAAE,OAAO,CAAA;QACjB,gBAAgB,CAAC,EAAE,OAAO,CAAA;KAC3B,CAAA;CACF,GAAG,IAAI,CAAC,MAAM,EAAE,IAAI,GAAG,QAAQ,GAAG,QAAQ,CAAC,GAC1C,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAA;AAE7B;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CA8HpF"}
|
|
@@ -1,7 +1,15 @@
|
|
|
1
|
+
import { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage';
|
|
2
|
+
import { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
1
3
|
import { lexicalEditor } from '@payloadcms/richtext-lexical';
|
|
2
4
|
import { buildConfig as payloadBuildConfig } from 'payload';
|
|
5
|
+
import { getTokenStore } from '../auth/token-store.js';
|
|
6
|
+
import { ENV_CONFIG, getEnvironment } from '../constants.js';
|
|
7
|
+
import { contentAPIAdapter } from '../db-content-api/index.js';
|
|
8
|
+
import { health } from '../endpoints/health.js';
|
|
3
9
|
import { oAuth2Plugin } from '../oauth/index.js';
|
|
4
|
-
import {
|
|
10
|
+
import { createStorageClient } from '../storage-content-api/client.js';
|
|
11
|
+
import { getGenerateSignedURLHandler } from '../storage-content-api/client-uploads/generateSignedURL.js';
|
|
12
|
+
import { contentApiStorageAdapter } from '../storage-content-api/index.js';
|
|
5
13
|
/**
|
|
6
14
|
* Figma platform wrapper for Payload's buildConfig.
|
|
7
15
|
* Automatically injects:
|
|
@@ -11,16 +19,115 @@ import { figmaContentSystem } from './adapter.js';
|
|
|
11
19
|
*
|
|
12
20
|
* @param config - Payload configuration (db and secret omitted, editor optional)
|
|
13
21
|
* @returns Promise<SanitizedConfig> - Built Payload configuration
|
|
14
|
-
*/ export async function
|
|
22
|
+
*/ export async function buildFigmaConfig(config) {
|
|
23
|
+
// Validate required environment variable
|
|
24
|
+
if (!config.figma.contentSystemId) {
|
|
25
|
+
throw new Error('FIGMA_CONTENT_SYSTEM_ID is required. ' + 'Ensure your .env file contains: FIGMA_CONTENT_SYSTEM_ID=your-content-system-id');
|
|
26
|
+
}
|
|
27
|
+
const env = getEnvironment();
|
|
28
|
+
const url = process.env.FIGMA_CONTENT_API_URL || ENV_CONFIG[env].contentApiUrl;
|
|
29
|
+
const { contentSystemId } = config.figma;
|
|
30
|
+
// Determine database adapter based on environment
|
|
31
|
+
let db;
|
|
32
|
+
if (config.figma.useContentSystem === false) {
|
|
33
|
+
db = config.db;
|
|
34
|
+
} else if (process.env.FIGMA_CONTENT_API_ACCESS_KEY) {
|
|
35
|
+
db = contentAPIAdapter({
|
|
36
|
+
auth: {
|
|
37
|
+
apiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY,
|
|
38
|
+
mode: 'apiKey'
|
|
39
|
+
},
|
|
40
|
+
contentSystemId,
|
|
41
|
+
url
|
|
42
|
+
});
|
|
43
|
+
} else if (process.env.FIGMA_DEV_JWT === 'true') {
|
|
44
|
+
db = contentAPIAdapter({
|
|
45
|
+
auth: {
|
|
46
|
+
mode: 'devJwt'
|
|
47
|
+
},
|
|
48
|
+
contentSystemId,
|
|
49
|
+
url
|
|
50
|
+
});
|
|
51
|
+
} else {
|
|
52
|
+
db = contentAPIAdapter({
|
|
53
|
+
auth: {
|
|
54
|
+
mode: 'tokenStore',
|
|
55
|
+
tokenStore: getTokenStore()
|
|
56
|
+
},
|
|
57
|
+
contentSystemId,
|
|
58
|
+
url
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
// Build storage plugin if there are upload collections and storage is not disabled
|
|
62
|
+
const uploadCollections = (config.collections || []).filter((c)=>c.upload);
|
|
63
|
+
let storagePlugin;
|
|
64
|
+
if (uploadCollections.length > 0 && config.figma.storage !== false) {
|
|
65
|
+
const storageConfig = process.env.FIGMA_CONTENT_API_ACCESS_KEY ? {
|
|
66
|
+
baseUrl: url,
|
|
67
|
+
contentApiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY
|
|
68
|
+
} : process.env.FIGMA_DEV_JWT === 'true' ? {
|
|
69
|
+
auth: {
|
|
70
|
+
mode: 'devJwt'
|
|
71
|
+
},
|
|
72
|
+
baseUrl: url,
|
|
73
|
+
contentSystemId
|
|
74
|
+
} : {
|
|
75
|
+
auth: {
|
|
76
|
+
mode: 'tokenStore',
|
|
77
|
+
tokenStore: getTokenStore()
|
|
78
|
+
},
|
|
79
|
+
baseUrl: url,
|
|
80
|
+
contentSystemId
|
|
81
|
+
};
|
|
82
|
+
const adapter = contentApiStorageAdapter(storageConfig);
|
|
83
|
+
const storageClient = createStorageClient(storageConfig);
|
|
84
|
+
const collectionsMap = uploadCollections.reduce((acc, c)=>{
|
|
85
|
+
acc[c.slug] = {
|
|
86
|
+
adapter,
|
|
87
|
+
disableLocalStorage: true
|
|
88
|
+
};
|
|
89
|
+
return acc;
|
|
90
|
+
}, {});
|
|
91
|
+
initClientUploads({
|
|
92
|
+
clientHandler: '@payloadcms/figma/client#ContentApiClientUploadHandler',
|
|
93
|
+
collections: collectionsMap,
|
|
94
|
+
config: config,
|
|
95
|
+
enabled: true,
|
|
96
|
+
serverHandler: getGenerateSignedURLHandler({
|
|
97
|
+
client: storageClient
|
|
98
|
+
}),
|
|
99
|
+
serverHandlerPath: '/content-api-storage-signed-url'
|
|
100
|
+
});
|
|
101
|
+
storagePlugin = cloudStoragePlugin({
|
|
102
|
+
collections: collectionsMap
|
|
103
|
+
});
|
|
104
|
+
}
|
|
15
105
|
// Build complete config with Figma platform defaults
|
|
16
106
|
const configWithFigmaDefaults = {
|
|
17
107
|
...config,
|
|
18
|
-
|
|
108
|
+
admin: {
|
|
109
|
+
// Auto-refresh tokens before expiry to prevent unexpected logouts.
|
|
110
|
+
// The project token (access token) expires in ~15 minutes, so the client
|
|
111
|
+
// will automatically refresh at ~14 minutes to keep the session alive.
|
|
112
|
+
autoRefresh: true,
|
|
113
|
+
...config.admin
|
|
114
|
+
},
|
|
115
|
+
custom: {
|
|
116
|
+
figma: config.figma || {}
|
|
117
|
+
},
|
|
118
|
+
db,
|
|
19
119
|
editor: config.editor ?? lexicalEditor(),
|
|
120
|
+
endpoints: [
|
|
121
|
+
...config.endpoints ?? [],
|
|
122
|
+
health
|
|
123
|
+
],
|
|
20
124
|
secret: 'MY_SECRET',
|
|
21
125
|
// Add oauth to plugins if not already present
|
|
22
126
|
plugins: [
|
|
23
127
|
...config.plugins ?? [],
|
|
128
|
+
...storagePlugin ? [
|
|
129
|
+
storagePlugin
|
|
130
|
+
] : [],
|
|
24
131
|
oAuth2Plugin({
|
|
25
132
|
collections: [
|
|
26
133
|
{
|
|
@@ -30,9 +137,9 @@ import { figmaContentSystem } from './adapter.js';
|
|
|
30
137
|
response_mode: 'query',
|
|
31
138
|
response_type: 'code'
|
|
32
139
|
},
|
|
33
|
-
clientID: process.env.FIGMA_OAUTH_CLIENT_ID,
|
|
140
|
+
clientID: process.env.FIGMA_OAUTH_CLIENT_ID || ENV_CONFIG[env].clientId,
|
|
34
141
|
clientSecret: process.env.FIGMA_OAUTH_CLIENT_SECRET,
|
|
35
|
-
identityMetadata:
|
|
142
|
+
identityMetadata: ENV_CONFIG[env].identityMetadata,
|
|
36
143
|
scope: [
|
|
37
144
|
'current_user:read'
|
|
38
145
|
],
|
|
@@ -40,9 +147,8 @@ import { figmaContentSystem } from './adapter.js';
|
|
|
40
147
|
usernameField: 'email'
|
|
41
148
|
}
|
|
42
149
|
],
|
|
43
|
-
debug:
|
|
44
|
-
disabled: false
|
|
45
|
-
redirectServerURL: 'http://localhost:3000'
|
|
150
|
+
debug: !!process.env.DEBUG,
|
|
151
|
+
disabled: false
|
|
46
152
|
})
|
|
47
153
|
]
|
|
48
154
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugin/build-config.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from 'payload'\n\nimport { lexicalEditor } from '@payloadcms/richtext-lexical'\nimport { buildConfig as payloadBuildConfig } from 'payload'\n\nimport { oAuth2Plugin } from '../oauth/index.js'\nimport { figmaContentSystem } from './adapter.js'\n\n/**\n * Configuration type for Payload projects on the Figma platform.\n *\n * Differences from standard Payload Config:\n * - `db`: Omitted (auto-injected by Figma platform)\n * - `secret`: Omitted (auto-injected by Figma platform)\n * - `editor`: Optional (defaults to lexicalEditor() if not provided)\n *\n * @example\n * // Minimal config\n * const config: FigmaConfig = {\n * collections: [...]\n * }\n *\n * @example\n * // With custom editor\n * const config: FigmaConfig = {\n * collections: [...],\n * editor: lexicalEditor({ features: [...] })\n * }\n */\nexport type FigmaConfig = {\n editor?: Config['editor']\n} & {\n figma: {\n region: string\n tenantId: string\n useContentSystem?: boolean\n }\n} & Omit<Config, 'editor' | 'secret' | 'db'> &\n Partial<Pick<Config, 'db'>>\n\n/**\n * Figma platform wrapper for Payload's buildConfig.\n * Automatically injects:\n * - Figma database adapter\n * - Secret (platform-provided)\n * - Default lexicalEditor (if no custom editor specified)\n *\n * @param config - Payload configuration (db and secret omitted, editor optional)\n * @returns Promise<SanitizedConfig> - Built Payload configuration\n */\nexport async function buildConfig(config: FigmaConfig): Promise<SanitizedConfig> {\n // Build complete config with Figma platform defaults\n const configWithFigmaDefaults: Config = {\n ...config,\n db: config.figma.useContentSystem ? figmaContentSystem() : config.db!,\n editor: config.editor ?? lexicalEditor(),\n secret: 'MY_SECRET',\n // Add oauth to plugins if not already present\n plugins: [\n ...(config.plugins ?? []),\n oAuth2Plugin({\n collections: [\n {\n slug: 'users',\n // Use adapter because Figma app doesn't support OIDC scopes\n authorizationURLParams: {\n response_mode: 'query',\n response_type: 'code',\n },\n clientID: process.env.FIGMA_OAUTH_CLIENT_ID!,\n clientSecret: process.env.FIGMA_OAUTH_CLIENT_SECRET,\n identityMetadata: 'https://staging.figma.com/.well-known/openid-configuration',\n scope: ['current_user:read'],\n token: 'id_token', // Adapter creates JWT id_token from Figma user info\n usernameField: 'email',\n },\n ],\n debug: true,\n disabled: false,\n redirectServerURL: 'http://localhost:3000',\n }),\n ],\n }\n\n // Delegate to Payload's buildConfig\n return await payloadBuildConfig(configWithFigmaDefaults)\n}\n"],"names":["lexicalEditor","buildConfig","payloadBuildConfig","oAuth2Plugin","figmaContentSystem","config","configWithFigmaDefaults","db","figma","useContentSystem","editor","secret","plugins","collections","slug","authorizationURLParams","response_mode","response_type","clientID","process","env","FIGMA_OAUTH_CLIENT_ID","clientSecret","FIGMA_OAUTH_CLIENT_SECRET","identityMetadata","scope","token","usernameField","debug","disabled","redirectServerURL"],"mappings":"AAEA,SAASA,aAAa,QAAQ,+BAA8B;AAC5D,SAASC,eAAeC,kBAAkB,QAAQ,UAAS;AAE3D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,kBAAkB,QAAQ,eAAc;AAkCjD;;;;;;;;;CASC,GACD,OAAO,eAAeH,YAAYI,MAAmB;IACnD,qDAAqD;IACrD,MAAMC,0BAAkC;QACtC,GAAGD,MAAM;QACTE,IAAIF,OAAOG,KAAK,CAACC,gBAAgB,GAAGL,uBAAuBC,OAAOE,EAAE;QACpEG,QAAQL,OAAOK,MAAM,IAAIV;QACzBW,QAAQ;QACR,8CAA8C;QAC9CC,SAAS;eACHP,OAAOO,OAAO,IAAI,EAAE;YACxBT,aAAa;gBACXU,aAAa;oBACX;wBACEC,MAAM;wBACN,4DAA4D;wBAC5DC,wBAAwB;4BACtBC,eAAe;4BACfC,eAAe;wBACjB;wBACAC,UAAUC,QAAQC,GAAG,CAACC,qBAAqB;wBAC3CC,cAAcH,QAAQC,GAAG,CAACG,yBAAyB;wBACnDC,kBAAkB;wBAClBC,OAAO;4BAAC;yBAAoB;wBAC5BC,OAAO;wBACPC,eAAe;oBACjB;iBACD;gBACDC,OAAO;gBACPC,UAAU;gBACVC,mBAAmB;YACrB;SACD;IACH;IAEA,oCAAoC;IACpC,OAAO,MAAM5B,mBAAmBI;AAClC"}
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/build-config.ts"],"sourcesContent":["import type { Config, SanitizedConfig } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { lexicalEditor } from '@payloadcms/richtext-lexical'\nimport { buildConfig as payloadBuildConfig } from 'payload'\n\nimport type { StorageClientConfig } from '../storage-content-api/index.js'\n\nimport { getTokenStore } from '../auth/token-store.js'\nimport { ENV_CONFIG, getEnvironment } from '../constants.js'\nimport { contentAPIAdapter } from '../db-content-api/index.js'\nimport { health } from '../endpoints/health.js'\nimport { oAuth2Plugin } from '../oauth/index.js'\nimport { createStorageClient } from '../storage-content-api/client.js'\nimport { getGenerateSignedURLHandler } from '../storage-content-api/client-uploads/generateSignedURL.js'\nimport { contentApiStorageAdapter } from '../storage-content-api/index.js'\n\n/**\n * Configuration type for Payload projects on the Figma platform.\n *\n * Differences from standard Payload Config:\n * - `db`: Omitted (auto-injected by Figma platform)\n * - `secret`: Omitted (auto-injected by Figma platform)\n * - `editor`: Optional (defaults to lexicalEditor() if not provided)\n *\n * @example\n * // Minimal config\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!\n * },\n * collections: [...]\n * }\n *\n * @example\n * // With custom editor\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!\n * },\n * collections: [...],\n * editor: lexicalEditor({ features: [...] })\n * }\n *\n * @example\n * // Disable Content System (use custom db)\n * const config: FigmaConfig = {\n * figma: {\n * contentSystemId: process.env.FIGMA_CONTENT_SYSTEM_ID!,\n * useContentSystem: false\n * },\n * db: mongooseAdapter({ url: process.env.DATABASE_URI }),\n * collections: [...]\n * }\n */\nexport type FigmaConfig = {\n editor?: Config['editor']\n} & {\n figma: {\n contentSystemId: string\n storage?: boolean\n useContentSystem?: boolean\n }\n} & Omit<Config, 'db' | 'editor' | 'secret'> &\n Partial<Pick<Config, 'db'>>\n\n/**\n * Figma platform wrapper for Payload's buildConfig.\n * Automatically injects:\n * - Figma database adapter\n * - Secret (platform-provided)\n * - Default lexicalEditor (if no custom editor specified)\n *\n * @param config - Payload configuration (db and secret omitted, editor optional)\n * @returns Promise<SanitizedConfig> - Built Payload configuration\n */\nexport async function buildFigmaConfig(config: FigmaConfig): Promise<SanitizedConfig> {\n // Validate required environment variable\n if (!config.figma.contentSystemId) {\n throw new Error(\n 'FIGMA_CONTENT_SYSTEM_ID is required. ' +\n 'Ensure your .env file contains: FIGMA_CONTENT_SYSTEM_ID=your-content-system-id',\n )\n }\n\n const env = getEnvironment()\n const url = process.env.FIGMA_CONTENT_API_URL || ENV_CONFIG[env].contentApiUrl\n const { contentSystemId } = config.figma\n\n // Determine database adapter based on environment\n let db: Config['db']\n\n if (config.figma.useContentSystem === false) {\n db = config.db!\n } else if (process.env.FIGMA_CONTENT_API_ACCESS_KEY) {\n db = contentAPIAdapter({\n auth: { apiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY, mode: 'apiKey' },\n contentSystemId,\n url,\n })\n } else if (process.env.FIGMA_DEV_JWT === 'true') {\n db = contentAPIAdapter({\n auth: { mode: 'devJwt' },\n contentSystemId,\n url,\n })\n } else {\n db = contentAPIAdapter({\n auth: { mode: 'tokenStore', tokenStore: getTokenStore() },\n contentSystemId,\n url,\n })\n }\n\n // Build storage plugin if there are upload collections and storage is not disabled\n const uploadCollections = (config.collections || []).filter((c) => c.upload)\n let storagePlugin: ReturnType<typeof cloudStoragePlugin> | undefined\n\n if (uploadCollections.length > 0 && config.figma.storage !== false) {\n const storageConfig: StorageClientConfig = process.env.FIGMA_CONTENT_API_ACCESS_KEY\n ? { baseUrl: url, contentApiKey: process.env.FIGMA_CONTENT_API_ACCESS_KEY }\n : process.env.FIGMA_DEV_JWT === 'true'\n ? {\n auth: { mode: 'devJwt' },\n baseUrl: url,\n contentSystemId,\n }\n : {\n auth: { mode: 'tokenStore', tokenStore: getTokenStore() },\n baseUrl: url,\n contentSystemId,\n }\n\n const adapter = contentApiStorageAdapter(storageConfig)\n const storageClient = createStorageClient(storageConfig)\n\n const collectionsMap = uploadCollections.reduce(\n (acc, c) => {\n acc[c.slug] = { adapter, disableLocalStorage: true }\n return acc\n },\n {} as Record<string, { adapter: typeof adapter; disableLocalStorage: boolean }>,\n )\n\n initClientUploads({\n clientHandler: '@payloadcms/figma/client#ContentApiClientUploadHandler',\n collections: collectionsMap,\n config: config as unknown as Config,\n enabled: true,\n serverHandler: getGenerateSignedURLHandler({ client: storageClient }),\n serverHandlerPath: '/content-api-storage-signed-url',\n })\n\n storagePlugin = cloudStoragePlugin({ collections: collectionsMap })\n }\n\n // Build complete config with Figma platform defaults\n const configWithFigmaDefaults: Config = {\n ...config,\n admin: {\n // Auto-refresh tokens before expiry to prevent unexpected logouts.\n // The project token (access token) expires in ~15 minutes, so the client\n // will automatically refresh at ~14 minutes to keep the session alive.\n autoRefresh: true,\n ...config.admin,\n },\n custom: {\n figma: config.figma || {},\n },\n db,\n editor: config.editor ?? lexicalEditor(),\n endpoints: [...(config.endpoints ?? []), health],\n secret: 'MY_SECRET',\n // Add oauth to plugins if not already present\n plugins: [\n ...(config.plugins ?? []),\n ...(storagePlugin ? [storagePlugin] : []),\n oAuth2Plugin({\n collections: [\n {\n slug: 'users',\n // Use adapter because Figma app doesn't support OIDC scopes\n authorizationURLParams: {\n response_mode: 'query',\n response_type: 'code',\n },\n clientID: process.env.FIGMA_OAUTH_CLIENT_ID || ENV_CONFIG[env].clientId,\n clientSecret: process.env.FIGMA_OAUTH_CLIENT_SECRET,\n identityMetadata: ENV_CONFIG[env].identityMetadata,\n scope: ['current_user:read'],\n token: 'id_token', // Adapter creates JWT id_token from Figma user info\n usernameField: 'email',\n },\n ],\n debug: !!process.env.DEBUG,\n disabled: false,\n }),\n ],\n }\n\n // Delegate to Payload's buildConfig\n return await payloadBuildConfig(configWithFigmaDefaults)\n}\n"],"names":["cloudStoragePlugin","initClientUploads","lexicalEditor","buildConfig","payloadBuildConfig","getTokenStore","ENV_CONFIG","getEnvironment","contentAPIAdapter","health","oAuth2Plugin","createStorageClient","getGenerateSignedURLHandler","contentApiStorageAdapter","buildFigmaConfig","config","figma","contentSystemId","Error","env","url","process","FIGMA_CONTENT_API_URL","contentApiUrl","db","useContentSystem","FIGMA_CONTENT_API_ACCESS_KEY","auth","apiKey","mode","FIGMA_DEV_JWT","tokenStore","uploadCollections","collections","filter","c","upload","storagePlugin","length","storage","storageConfig","baseUrl","contentApiKey","adapter","storageClient","collectionsMap","reduce","acc","slug","disableLocalStorage","clientHandler","enabled","serverHandler","client","serverHandlerPath","configWithFigmaDefaults","admin","autoRefresh","custom","editor","endpoints","secret","plugins","authorizationURLParams","response_mode","response_type","clientID","FIGMA_OAUTH_CLIENT_ID","clientId","clientSecret","FIGMA_OAUTH_CLIENT_SECRET","identityMetadata","scope","token","usernameField","debug","DEBUG","disabled"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,aAAa,QAAQ,+BAA8B;AAC5D,SAASC,eAAeC,kBAAkB,QAAQ,UAAS;AAI3D,SAASC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