@payloadcms/figma 0.0.1-alpha.28 → 0.0.1-alpha.29
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 +3 -0
- package/dist/api/control-plane.d.ts.map +1 -1
- package/dist/api/control-plane.js +6 -2
- package/dist/api/control-plane.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/oauth-flow.d.ts +1 -1
- package/dist/auth/oauth-flow.d.ts.map +1 -1
- package/dist/auth/oauth-flow.js +2 -2
- package/dist/auth/oauth-flow.js.map +1 -1
- package/dist/cli.js +2 -0
- package/dist/cli.js.map +1 -1
- package/dist/commands/deploy.d.ts +2 -0
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +36 -43
- package/dist/commands/deploy.js.map +1 -1
- package/dist/config/oauth.d.ts +5 -0
- package/dist/config/oauth.d.ts.map +1 -1
- package/dist/config/oauth.js +5 -1
- package/dist/config/oauth.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/index.d.ts.map +1 -1
- package/dist/oauth/index.js +14 -2
- package/dist/oauth/index.js.map +1 -1
- package/dist/oauth/strategy/index.js +2 -2
- package/dist/oauth/strategy/index.js.map +1 -1
- package/dist/oauth/types.d.ts +5 -5
- package/dist/oauth/types.d.ts.map +1 -1
- package/dist/oauth/types.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.js +1 -1
- package/dist/oauth/utilities/refreshTokens.js.map +1 -1
- package/dist/templates/README.md +19 -0
- package/dist/utils/env-management.d.ts +8 -0
- package/dist/utils/env-management.d.ts.map +1 -1
- package/dist/utils/env-management.js +32 -0
- package/dist/utils/env-management.js.map +1 -1
- package/dist/utils/formatter.d.ts.map +1 -1
- package/dist/utils/formatter.js +1 -7
- package/dist/utils/formatter.js.map +1 -1
- package/dist/utils/messages.js +2 -2
- package/dist/utils/messages.js.map +1 -1
- package/dist/utils/payload-package-check.d.ts.map +1 -1
- package/dist/utils/payload-package-check.js +9 -6
- package/dist/utils/payload-package-check.js.map +1 -1
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +7 -3
- package/dist/utils/project.js.map +1 -1
- package/dist/utils/typescript-validator.d.ts.map +1 -1
- package/dist/utils/typescript-validator.js +1 -6
- package/dist/utils/typescript-validator.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/deploy.ts"],"sourcesContent":["import * as p from '@clack/prompts'\nimport { spawn } from 'child_process'\nimport path from 'path'\nimport pc from 'picocolors'\n\nimport { createDeployment, performDeployment } from '../api/control-plane.js'\nimport { getValidAccessToken } from '../auth/oauth-flow.js'\nimport { getTokenStore } from '../auth/token-store.js'\nimport { collectStaticAssets, createLambdaZip, getFileSize } from '../utils/asset-collection.js'\nimport { detectBuild, getBuildCommand } from '../utils/build-detection.js'\nimport * as log from '../utils/log.js'\nimport { getPackageManager } from '../utils/package-manager.js'\nimport { isInProjectDirectory } from '../utils/project.js'\nimport { uploadLambdaZip, uploadStaticAssets } from '../utils/s3-upload.js'\nimport { loginCommand } from './login.js'\n\n/**\n * Options for deploy command\n */\nexport interface DeployCommandOptions {\n /** Enable debug mode */\n debug?: boolean\n /** Tenant ID */\n id?: string\n /** Skip confirmation prompts */\n yes?: boolean\n}\n\n/**\n * Format bytes to human-readable string\n */\nfunction formatBytes(bytes: number): string {\n if (bytes === 0) {\n return '0 B'\n }\n const k = 1024\n const sizes = ['B', 'KB', 'MB', 'GB']\n const i = Math.floor(Math.log(bytes) / Math.log(k))\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`\n}\n\n/**\n * Format date to human-readable string in local time\n */\nfunction formatDate(date: Date): string {\n return date.toLocaleString('en-US', {\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n month: 'long',\n timeZoneName: 'short',\n year: 'numeric',\n })\n}\n\n/**\n * Execute the deploy command\n *\n * @param options - Command options\n */\nexport async function deployCommand(options: DeployCommandOptions): Promise<void> {\n const projectPath = process.cwd()\n const spinner = p.spinner()\n\n if (!options.id) {\n p.log.error(pc.red('✗ Tenant ID is required. Use --id <tenant_id> to specify.'))\n process.exit(1)\n }\n\n const tenantId = options.id\n\n try {\n // ===== PRE-FLIGHT CHECKS =====\n\n // Check if in project directory\n if (!(await isInProjectDirectory(projectPath))) {\n p.log.error(pc.red(\"✗ 'deploy' command is not available outside of a Payload project.\"))\n p.note(\n 'Create a project or connect an existing one to Figma: npx @payloadcms/figma init',\n 'Tip',\n )\n process.exit(1)\n }\n\n // Check authentication\n const tokenStore = getTokenStore()\n\n let accessToken = await getValidAccessToken(tokenStore)\n if (!accessToken) {\n p.log.message('Please log in to continue')\n await loginCommand()\n accessToken = await getValidAccessToken(tokenStore)\n if (!accessToken) {\n p.log.error(pc.red('✗ Authentication failed'))\n process.exit(1)\n }\n }\n\n // ===== BUILD VALIDATION =====\n\n spinner.start('Checking for build...')\n let buildInfo = await detectBuild(projectPath)\n\n if (!buildInfo) {\n spinner.stop(pc.yellow('⚠ No build found for this project.'))\n\n // Try to find build command\n const buildCmd = await getBuildCommand(projectPath)\n\n if (!buildCmd) {\n p.log.error('No build script found in package.json')\n p.note('Add a build script to package.json: \"build\": \"next build\"', 'Tip')\n process.exit(1)\n }\n\n // Prompt to run build\n if (!options.yes) {\n const shouldBuild = await p.confirm({\n initialValue: true,\n message: `Build command found in package.json. Run it?`,\n })\n\n if (p.isCancel(shouldBuild) || !shouldBuild) {\n p.log.message('Cancelling deployment...')\n process.exit(0)\n }\n }\n\n // Run build\n const packageManager = await getPackageManager(projectPath)\n const buildCommand = `${packageManager} run build`\n spinner.stop(`Running ${buildCommand}...\\n`)\n\n try {\n // Stream build output to user with formatting\n const buildProcess = spawn(packageManager, ['run', 'build'], {\n cwd: projectPath,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n // Indent and dim output\n buildProcess.stdout?.on('data', (data) => {\n const lines = data.toString().split('\\n')\n lines.forEach((line: string) => {\n if (line.trim()) {\n // eslint-disable-next-line no-console\n console.log(pc.dim(` ${line}`)) // Standard output\n }\n })\n })\n\n buildProcess.stderr?.on('data', (data) => {\n const lines = data.toString().split('\\n')\n lines.forEach((line: string) => {\n if (line.trim()) {\n // eslint-disable-next-line no-console\n console.log(pc.dim(` ${line}`)) // Standard error\n }\n })\n })\n\n const exitCode = await new Promise<number>((resolve) => {\n buildProcess.on('close', resolve)\n })\n\n if (exitCode !== 0) {\n throw new Error(`Build process exited with code ${exitCode}`)\n }\n\n p.log.success(pc.green('✓ Build completed'))\n } catch (error) {\n p.log.error(pc.red('✗ Build failed'))\n if (error instanceof Error && options.debug) {\n log.error(`Build error: ${error.message}`)\n }\n process.exit(1)\n }\n\n // Re-check for build\n buildInfo = await detectBuild(projectPath)\n if (!buildInfo) {\n p.log.error(pc.red('✗ Build completed but standalone build not found'))\n p.note('Ensure next.config.js has output: \"standalone\"', 'Check Lambda Configuration')\n process.exit(1)\n }\n } else {\n spinner.stop(pc.green('✓ Build found'))\n p.note(\n [\n `${pc.cyan('Build ID:')} ${buildInfo.buildId}`,\n `${pc.cyan('Date:')} ${formatDate(buildInfo.timestamp)}`,\n ].join('\\n'),\n 'Build Details',\n )\n }\n\n // ===== DEPLOYMENT PREPARATION =====\n\n // Create Lambda zip\n spinner.start('Creating deployment package...')\n try {\n await createLambdaZip(projectPath)\n spinner.stop(pc.green('✓ Deployment package created'))\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to create deployment package'))\n throw error\n }\n\n // Collect static assets\n spinner.start('Collecting static assets...')\n const staticAssets = await collectStaticAssets(projectPath)\n const zipPath = path.join(projectPath, 'lambda.zip')\n const zipSize = await getFileSize(zipPath)\n spinner.stop(pc.green(`✓ ${staticAssets.length} static assets detected`))\n\n log.debug(`Lambda zip size: ${formatBytes(zipSize)}`)\n log.debug(`Static assets: ${staticAssets.length} files`)\n\n // ===== DEPLOYMENT CONFIRMATION =====\n\n if (!options.yes) {\n p.note(\n [\n `${pc.cyan('Build ID:')} ${buildInfo.buildId}`,\n `${pc.cyan('Date:')} ${formatDate(buildInfo.timestamp)}`,\n `${pc.cyan('Code size:')} ${formatBytes(zipSize)}`,\n `${pc.cyan('Static assets:')} ${staticAssets.length} files`,\n ].join('\\n'),\n 'Details',\n )\n\n const shouldDeploy = await p.confirm({\n initialValue: true,\n message: 'Deploy this build to Figma?',\n })\n\n if (p.isCancel(shouldDeploy) || !shouldDeploy) {\n p.log.message('Cancelling deployment...')\n process.exit(0)\n }\n }\n\n // ===== DEPLOYMENT EXECUTION =====\n\n // Step 1: Create deployment\n spinner.start('Creating deployment...')\n let deploymentId: string\n let codeUploadUrl: string\n let staticAssetUploadUrls: Record<string, string>\n\n try {\n const createResponse = await createDeployment(accessToken, tenantId, {\n staticAssets,\n })\n\n deploymentId = createResponse.deploymentId\n codeUploadUrl = createResponse.codeUploadUrl\n staticAssetUploadUrls = createResponse.staticAssetUploadUrls\n\n log.debug(`Deployment ID: ${deploymentId}`)\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to create deployment'))\n throw error\n }\n\n // Step 2: Upload code\n spinner.message(`Uploading code (${formatBytes(zipSize)})...`)\n try {\n await uploadLambdaZip(zipPath, codeUploadUrl)\n spinner.stop(pc.green(`✓ Code uploaded (${formatBytes(zipSize)})`))\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to upload code'))\n throw error\n }\n\n // Step 3: Upload static assets\n if (staticAssets.length > 0) {\n spinner.start('Uploading static assets...')\n\n try {\n const uploadResults = await uploadStaticAssets(\n projectPath,\n staticAssetUploadUrls,\n (uploaded, total) => {\n spinner.message(`Uploading static assets (${uploaded}/${total})...`)\n },\n )\n\n if (uploadResults.assetsFailed > 0) {\n spinner.stop(\n pc.yellow(\n `⚠ ${uploadResults.assetsUploaded}/${staticAssets.length} assets uploaded (${uploadResults.assetsFailed} failed)`,\n ),\n )\n p.log.warning(\n `${uploadResults.assetsFailed} assets failed to upload. Deployment may be incomplete.`,\n )\n } else {\n spinner.stop(\n pc.green(\n `✓ Static assets uploaded (${uploadResults.assetsUploaded} files, ${formatBytes(uploadResults.totalBytesUploaded)})`,\n ),\n )\n }\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to upload assets'))\n throw error\n }\n }\n\n // Step 4: Perform deployment\n spinner.start('Performing deployment...')\n try {\n await performDeployment(accessToken, tenantId, {\n deploymentId,\n })\n spinner.stop(pc.green('✓ Deployment initiated'))\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to perform deployment'))\n throw error\n }\n\n // TODO: Add deployment progress tracking\n // Future: Poll deployment status and show progress\n // API endpoint: GET /v1/tenant/{tenant_id}/deploy/{deployment_id}/status\n\n // Success output\n p.log.message('This usually takes 2-3 minutes to complete.')\n\n // TODO: Get tenant details for URL using getTenantDetails\n // TODO: Display next steps with url to manage their CMS ie. https://staging.figma.com/files/1234/cms/manager/12345678\n } catch (error) {\n spinner.stop(pc.red('✗ Failed'))\n const message = error instanceof Error ? error.message : 'Unknown error'\n p.log.error(pc.red(`✗ ${message}`))\n if (options.debug && error instanceof Error && error.stack) {\n log.error(`Stack trace: ${error.stack}`)\n }\n process.exit(1)\n }\n}\n"],"names":["p","spawn","path","pc","createDeployment","performDeployment","getValidAccessToken","getTokenStore","collectStaticAssets","createLambdaZip","getFileSize","detectBuild","getBuildCommand","log","getPackageManager","isInProjectDirectory","uploadLambdaZip","uploadStaticAssets","loginCommand","formatBytes","bytes","k","sizes","i","Math","floor","parseFloat","pow","toFixed","formatDate","date","toLocaleString","day","hour","minute","month","timeZoneName","year","deployCommand","options","projectPath","process","cwd","spinner","id","error","red","exit","tenantId","note","tokenStore","accessToken","message","start","buildInfo","stop","yellow","buildCmd","yes","shouldBuild","confirm","initialValue","isCancel","packageManager","buildCommand","buildProcess","stdio","stdout","on","data","lines","toString","split","forEach","line","trim","console","dim","stderr","exitCode","Promise","resolve","Error","success","green","debug","cyan","buildId","timestamp","join","staticAssets","zipPath","zipSize","length","shouldDeploy","deploymentId","codeUploadUrl","staticAssetUploadUrls","createResponse","uploadResults","uploaded","total","assetsFailed","assetsUploaded","warning","totalBytesUploaded","stack"],"mappings":"AAAA,YAAYA,OAAO,iBAAgB;AACnC,SAASC,KAAK,QAAQ,gBAAe;AACrC,OAAOC,UAAU,OAAM;AACvB,OAAOC,QAAQ,aAAY;AAE3B,SAASC,gBAAgB,EAAEC,iBAAiB,QAAQ,0BAAyB;AAC7E,SAASC,mBAAmB,QAAQ,wBAAuB;AAC3D,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,mBAAmB,EAAEC,eAAe,EAAEC,WAAW,QAAQ,+BAA8B;AAChG,SAASC,WAAW,EAAEC,eAAe,QAAQ,8BAA6B;AAC1E,YAAYC,SAAS,kBAAiB;AACtC,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,oBAAoB,QAAQ,sBAAqB;AAC1D,SAASC,eAAe,EAAEC,kBAAkB,QAAQ,wBAAuB;AAC3E,SAASC,YAAY,QAAQ,aAAY;AAczC;;CAEC,GACD,SAASC,YAAYC,KAAa;IAChC,IAAIA,UAAU,GAAG;QACf,OAAO;IACT;IACA,MAAMC,IAAI;IACV,MAAMC,QAAQ;QAAC;QAAK;QAAM;QAAM;KAAK;IACrC,MAAMC,IAAIC,KAAKC,KAAK,CAACD,KAAKX,GAAG,CAACO,SAASI,KAAKX,GAAG,CAACQ;IAChD,OAAO,GAAGK,WAAW,AAACN,CAAAA,QAAQI,KAAKG,GAAG,CAACN,GAAGE,EAAC,EAAGK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,CACX,GAAGL,cAAcG,YAAY,CAAC,uDAAuD,CAAC;gBAE1F,OAAO;oBACL3D,QAAQY,IAAI,CACVpD,GAAGiF,KAAK,CACN,CAAC,0BAA0B,EAAEe,cAAcI,cAAc,CAAC,QAAQ,EAAEpF,YAAYgF,cAAcM,kBAAkB,EAAE,CAAC,CAAC;gBAG1H;YACF,EAAE,OAAO5D,OAAO;gBACdF,QAAQY,IAAI,CAACpD,GAAG2C,GAAG,CAAC;gBACpB,MAAMD;YACR;QACF;QAEA,6BAA6B;QAC7BF,QAAQU,KAAK,CAAC;QACd,IAAI;YACF,MAAMhD,kBAAkB8C,aAAaH,UAAU;gBAC7C+C;YACF;YACApD,QAAQY,IAAI,CAACpD,GAAGiF,KAAK,CAAC;QACxB,EAAE,OAAOvC,OAAO;YACdF,QAAQY,IAAI,CAACpD,GAAG2C,GAAG,CAAC;YACpB,MAAMD;QACR;QAEA,yCAAyC;QACzC,mDAAmD;QACnD,yEAAyE;QAEzE,iBAAiB;QACjB7C,EAAEa,GAAG,CAACuC,OAAO,CAAC;IAEd,0DAA0D;IAC1D,sHAAsH;IACxH,EAAE,OAAOP,OAAO;QACdF,QAAQY,IAAI,CAACpD,GAAG2C,GAAG,CAAC;QACpB,MAAMM,UAAUP,iBAAiBqC,QAAQrC,MAAMO,OAAO,GAAG;QACzDpD,EAAEa,GAAG,CAACgC,KAAK,CAAC1C,GAAG2C,GAAG,CAAC,CAAC,EAAE,EAAEM,SAAS;QACjC,IAAIb,QAAQ8C,KAAK,IAAIxC,iBAAiBqC,SAASrC,MAAM6D,KAAK,EAAE;YAC1D7F,IAAIgC,KAAK,CAAC,CAAC,aAAa,EAAEA,MAAM6D,KAAK,EAAE;QACzC;QACAjE,QAAQM,IAAI,CAAC;IACf;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/commands/deploy.ts"],"sourcesContent":["import * as p from '@clack/prompts'\nimport { spawn } from 'child_process'\nimport path from 'path'\nimport pc from 'picocolors'\n\nimport { createDeployment, performDeployment } from '../api/control-plane.js'\nimport { getValidAccessToken } from '../auth/oauth-flow.js'\nimport { getTokenStore } from '../auth/token-store.js'\nimport { collectStaticAssets, createLambdaZip, getFileSize } from '../utils/asset-collection.js'\nimport { detectBuild, getBuildCommand } from '../utils/build-detection.js'\nimport { getEnvVar } from '../utils/env-management.js'\nimport * as log from '../utils/log.js'\nimport { getPackageManager } from '../utils/package-manager.js'\nimport { isInProjectDirectory } from '../utils/project.js'\nimport { uploadLambdaZip, uploadStaticAssets } from '../utils/s3-upload.js'\nimport { loginCommand } from './login.js'\n\n/**\n * Options for deploy command\n */\nexport interface DeployCommandOptions {\n /** Enable debug mode */\n debug?: boolean\n /** Tenant ID */\n id?: string\n /** Skip the build step (use existing build) */\n skipBuild?: boolean\n /** Skip confirmation prompts */\n yes?: boolean\n}\n\n/**\n * Format bytes to human-readable string\n */\nfunction formatBytes(bytes: number): string {\n if (bytes === 0) {\n return '0 B'\n }\n const k = 1024\n const sizes = ['B', 'KB', 'MB', 'GB']\n const i = Math.floor(Math.log(bytes) / Math.log(k))\n return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`\n}\n\n/**\n * Format date to human-readable string in local time\n */\nfunction formatDate(date: Date): string {\n return date.toLocaleString('en-US', {\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n month: 'long',\n timeZoneName: 'short',\n year: 'numeric',\n })\n}\n\n/**\n * Execute the deploy command\n *\n * @param options - Command options\n */\nexport async function deployCommand(options: DeployCommandOptions): Promise<void> {\n const projectPath = process.cwd()\n const spinner = p.spinner()\n\n let tenantId = options.id\n if (!tenantId) {\n tenantId = (await getEnvVar(projectPath, 'FIGMA_TENANT_ID')) ?? undefined\n }\n if (!tenantId) {\n p.log.error(pc.red('✗ Tenant ID not found. Run `@payloadcms/figma init` first.'))\n process.exit(1)\n }\n\n try {\n // ===== PRE-FLIGHT CHECKS =====\n\n // Check if in project directory\n if (!(await isInProjectDirectory(projectPath))) {\n p.log.error(pc.red(\"✗ 'deploy' command is not available outside of a Payload project.\"))\n p.note(\n 'Create a project or connect an existing one to Figma: npx @payloadcms/figma init',\n 'Tip',\n )\n process.exit(1)\n }\n\n // Check authentication\n const tokenStore = getTokenStore()\n\n let accessToken = await getValidAccessToken(tokenStore)\n if (!accessToken) {\n p.log.message('Please log in to continue')\n await loginCommand()\n accessToken = await getValidAccessToken(tokenStore)\n if (!accessToken) {\n p.log.error(pc.red('✗ Authentication failed'))\n process.exit(1)\n }\n }\n\n // ===== BUILD =====\n\n let buildInfo: Awaited<ReturnType<typeof detectBuild>>\n\n if (options.skipBuild) {\n // User asserts build exists - verify it\n spinner.start('Checking for build...')\n buildInfo = await detectBuild(projectPath)\n\n if (!buildInfo) {\n spinner.stop(pc.red('✗ No build found'))\n p.log.error('Use deploy without --skip-build to build first.')\n process.exit(1)\n }\n\n spinner.stop(pc.green('✓ Build found'))\n p.note(\n [\n `${pc.cyan('Build ID:')} ${buildInfo.buildId}`,\n `${pc.cyan('Date:')} ${formatDate(buildInfo.timestamp)}`,\n ].join('\\n'),\n 'Build Details',\n )\n } else {\n // Always build (no prompt)\n const buildCmd = await getBuildCommand(projectPath)\n\n if (!buildCmd) {\n p.log.error('No build script found in package.json')\n p.note('Add a build script to package.json: \"build\": \"next build\"', 'Tip')\n process.exit(1)\n }\n\n const packageManager = await getPackageManager(projectPath)\n const buildCommand = `${packageManager} run build`\n p.log.step(`Running ${buildCommand}...\\n`)\n\n try {\n // Stream build output to user with formatting\n const buildProcess = spawn(packageManager, ['run', 'build'], {\n cwd: projectPath,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n // Indent and dim output\n buildProcess.stdout?.on('data', (data) => {\n const lines = data.toString().split('\\n')\n lines.forEach((line: string) => {\n if (line.trim()) {\n // eslint-disable-next-line no-console\n console.log(pc.dim(` ${line}`))\n }\n })\n })\n\n buildProcess.stderr?.on('data', (data) => {\n const lines = data.toString().split('\\n')\n lines.forEach((line: string) => {\n if (line.trim()) {\n // eslint-disable-next-line no-console\n console.log(pc.dim(` ${line}`))\n }\n })\n })\n\n const exitCode = await new Promise<number>((resolve) => {\n buildProcess.on('close', resolve)\n })\n\n if (exitCode !== 0) {\n throw new Error(`Build process exited with code ${exitCode}`)\n }\n\n p.log.success(pc.green('✓ Build completed'))\n } catch (error) {\n p.log.error(pc.red('✗ Build failed'))\n if (error instanceof Error && options.debug) {\n log.error(`Build error: ${error.message}`)\n }\n process.exit(1)\n }\n\n // Verify build output\n buildInfo = await detectBuild(projectPath)\n if (!buildInfo) {\n p.log.error(pc.red('✗ Build completed but standalone build not found'))\n p.note('Ensure next.config.js has output: \"standalone\"', 'Check Lambda Configuration')\n process.exit(1)\n }\n }\n\n // ===== DEPLOYMENT PREPARATION =====\n\n // Create Lambda zip\n spinner.start('Creating deployment package...')\n try {\n await createLambdaZip(projectPath)\n spinner.stop(pc.green('✓ Deployment package created'))\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to create deployment package'))\n throw error\n }\n\n // Collect static assets\n spinner.start('Collecting static assets...')\n const staticAssets = await collectStaticAssets(projectPath)\n const zipPath = path.join(projectPath, 'lambda.zip')\n const zipSize = await getFileSize(zipPath)\n spinner.stop(pc.green(`✓ ${staticAssets.length} static assets detected`))\n\n log.debug(`Lambda zip size: ${formatBytes(zipSize)}`)\n log.debug(`Static assets: ${staticAssets.length} files`)\n\n // ===== DEPLOYMENT CONFIRMATION =====\n\n if (!options.yes) {\n p.note(\n [\n `${pc.cyan('Build ID:')} ${buildInfo.buildId}`,\n `${pc.cyan('Date:')} ${formatDate(buildInfo.timestamp)}`,\n `${pc.cyan('Code size:')} ${formatBytes(zipSize)}`,\n `${pc.cyan('Static assets:')} ${staticAssets.length} files`,\n ].join('\\n'),\n 'Details',\n )\n }\n\n // ===== DEPLOYMENT EXECUTION =====\n\n // Step 1: Create deployment\n spinner.start('Creating deployment...')\n let deploymentId: string\n let codeUploadUrl: string\n let staticAssetUploadUrls: Record<string, string>\n\n try {\n const createResponse = await createDeployment(accessToken, tenantId, {\n staticAssets,\n })\n\n deploymentId = createResponse.deploymentId\n codeUploadUrl = createResponse.codeUploadUrl\n staticAssetUploadUrls = createResponse.staticAssetUploadUrls\n\n log.debug(`Deployment ID: ${deploymentId}`)\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to create deployment'))\n throw error\n }\n\n // Step 2: Upload code\n spinner.message(`Uploading code (${formatBytes(zipSize)})...`)\n try {\n await uploadLambdaZip(zipPath, codeUploadUrl)\n spinner.stop(pc.green(`✓ Code uploaded (${formatBytes(zipSize)})`))\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to upload code'))\n throw error\n }\n\n // Step 3: Upload static assets\n if (staticAssets.length > 0) {\n spinner.start('Uploading static assets...')\n\n try {\n const uploadResults = await uploadStaticAssets(\n projectPath,\n staticAssetUploadUrls,\n (uploaded, total) => {\n spinner.message(`Uploading static assets (${uploaded}/${total})...`)\n },\n )\n\n if (uploadResults.assetsFailed > 0) {\n spinner.stop(\n pc.yellow(\n `⚠ ${uploadResults.assetsUploaded}/${staticAssets.length} assets uploaded (${uploadResults.assetsFailed} failed)`,\n ),\n )\n p.log.warning(\n `${uploadResults.assetsFailed} assets failed to upload. Deployment may be incomplete.`,\n )\n } else {\n spinner.stop(\n pc.green(\n `✓ Static assets uploaded (${uploadResults.assetsUploaded} files, ${formatBytes(uploadResults.totalBytesUploaded)})`,\n ),\n )\n }\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to upload assets'))\n throw error\n }\n }\n\n // Step 4: Perform deployment\n spinner.start('Performing deployment...')\n let tenantDomains: string[] = []\n try {\n const result = await performDeployment(accessToken, tenantId, {\n deploymentId,\n })\n tenantDomains = result.tenantDomains ?? []\n spinner.stop(pc.green('✓ Deployment initiated'))\n } catch (error) {\n spinner.stop(pc.red('✗ Failed to perform deployment'))\n throw error\n }\n\n // TODO: Add deployment progress tracking\n // Future: Poll deployment status and show progress\n // API endpoint: GET /v1/tenant/{tenant_id}/deploy/{deployment_id}/status\n\n // Success output\n if (tenantDomains.length > 0) {\n p.log.step(`URL: ${pc.cyan(`https://${tenantDomains[0]}`)}`)\n }\n p.log.step('This usually takes 2-3 minutes to complete.')\n } catch (error) {\n spinner.stop(pc.red('✗ Failed'))\n const message = error instanceof Error ? error.message : 'Unknown error'\n p.log.error(pc.red(`✗ ${message}`))\n if (options.debug && error instanceof Error && error.stack) {\n log.error(`Stack trace: ${error.stack}`)\n }\n process.exit(1)\n }\n}\n"],"names":["p","spawn","path","pc","createDeployment","performDeployment","getValidAccessToken","getTokenStore","collectStaticAssets","createLambdaZip","getFileSize","detectBuild","getBuildCommand","getEnvVar","log","getPackageManager","isInProjectDirectory","uploadLambdaZip","uploadStaticAssets","loginCommand","formatBytes","bytes","k","sizes","i","Math","floor","parseFloat","pow","toFixed","formatDate","date","toLocaleString","day","hour","minute","month","timeZoneName","year","deployCommand","options","projectPath","process","cwd","spinner","tenantId","id","undefined","error","red","exit","note","tokenStore","accessToken","message","buildInfo","skipBuild","start","stop","green","cyan","buildId","timestamp","join","buildCmd","packageManager","buildCommand","step","buildProcess","stdio","stdout","on","data","lines","toString","split","forEach","line","trim","console","dim","stderr","exitCode","Promise","resolve","Error","success","debug","staticAssets","zipPath","zipSize","length","yes","deploymentId","codeUploadUrl","staticAssetUploadUrls","createResponse","uploadResults","uploaded","total","assetsFailed","yellow","assetsUploaded","warning","totalBytesUploaded","tenantDomains","result","stack"],"mappings":"AAAA,YAAYA,OAAO,iBAAgB;AACnC,SAASC,KAAK,QAAQ,gBAAe;AACrC,OAAOC,UAAU,OAAM;AACvB,OAAOC,QAAQ,aAAY;AAE3B,SAASC,gBAAgB,EAAEC,iBAAiB,QAAQ,0BAAyB;AAC7E,SAASC,mBAAmB,QAAQ,wBAAuB;AAC3D,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,mBAAmB,EAAEC,eAAe,EAAEC,WAAW,QAAQ,+BAA8B;AAChG,SAASC,WAAW,EAAEC,eAAe,QAAQ,8BAA6B;AAC1E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AAMM,OAAO,GAAG;QACzDtD,EAAEc,GAAG,CAACkC,KAAK,CAAC7C,GAAG8C,GAAG,CAAC,CAAC,EAAE,EAAEK,SAAS;QACjC,IAAId,QAAQ+C,KAAK,IAAIvC,iBAAiBqC,SAASrC,MAAM2D,KAAK,EAAE;YAC1D7F,IAAIkC,KAAK,CAAC,CAAC,aAAa,EAAEA,MAAM2D,KAAK,EAAE;QACzC;QACAjE,QAAQQ,IAAI,CAAC;IACf;AACF"}
|
package/dist/config/oauth.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import type { OAuthConfig } from '../auth/types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Default port for OAuth callback server
|
|
4
|
+
* Using a high port (34462) to avoid conflicts with common dev servers (3000, 8080, etc.)
|
|
5
|
+
*/
|
|
6
|
+
export declare const DEFAULT_CALLBACK_PORT = 34462;
|
|
2
7
|
export declare const URLS: Record<'prod' | 'staging', Pick<OAuthConfig, 'authorizationUrl' | 'refreshUrl' | 'tokenUrl'>>;
|
|
3
8
|
/**
|
|
4
9
|
* Figma OAuth2 configuration for public CLI client
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/config/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAInD,eAAO,MAAM,IAAI,EAAE,MAAM,CACvB,MAAM,GAAG,SAAS,EAClB,IAAI,CAAC,WAAW,EAAE,kBAAkB,GAAG,YAAY,GAAG,UAAU,CAAC,CAkBlE,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"oauth.d.ts","sourceRoot":"","sources":["../../src/config/oauth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAInD;;;GAGG;AACH,eAAO,MAAM,qBAAqB,QAAQ,CAAA;AAE1C,eAAO,MAAM,IAAI,EAAE,MAAM,CACvB,MAAM,GAAG,SAAS,EAClB,IAAI,CAAC,WAAW,EAAE,kBAAkB,GAAG,YAAY,GAAG,UAAU,CAAC,CAkBlE,CAAA;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,YAAY,EAAE,WAgB1B,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,2BAA2B,MAAM,CAAA"}
|
package/dist/config/oauth.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import { FIGMA_CLIENT_IDS } from '../constants.js';
|
|
2
|
+
/**
|
|
3
|
+
* Default port for OAuth callback server
|
|
4
|
+
* Using a high port (34462) to avoid conflicts with common dev servers (3000, 8080, etc.)
|
|
5
|
+
*/ export const DEFAULT_CALLBACK_PORT = 34462;
|
|
2
6
|
export const URLS = {
|
|
3
7
|
prod: {
|
|
4
8
|
authorizationUrl: 'https://www.figma.com/oauth',
|
|
@@ -27,7 +31,7 @@ export const URLS = {
|
|
|
27
31
|
clientId: process.env.FIGMA_CLIENT_ID || FIGMA_CLIENT_IDS.staging,
|
|
28
32
|
// No client secret - this is a public OAuth client using PKCE
|
|
29
33
|
// Public clients cannot securely store secrets in CLI environments
|
|
30
|
-
redirectUri: process.env.FIGMA_REDIRECT_URI ||
|
|
34
|
+
redirectUri: process.env.FIGMA_REDIRECT_URI || `http://localhost:${DEFAULT_CALLBACK_PORT}/callback`,
|
|
31
35
|
// Only current_user:read scope is needed for basic user info
|
|
32
36
|
scopes: [
|
|
33
37
|
'current_user:read'
|
package/dist/config/oauth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/oauth.ts"],"sourcesContent":["import type { OAuthConfig } from '../auth/types.js'\n\nimport { FIGMA_CLIENT_IDS } from '../constants.js'\n\nexport const URLS: Record<\n 'prod' | 'staging',\n Pick<OAuthConfig, 'authorizationUrl' | 'refreshUrl' | 'tokenUrl'>\n> = {\n prod: {\n authorizationUrl: 'https://www.figma.com/oauth',\n refreshUrl: 'https://api.figma.com/v1/oauth/refresh',\n tokenUrl: 'https://api.figma.com/v1/oauth/token',\n },\n staging: {\n authorizationUrl: process.env.FIGMA_AUTH_URL\n ? `${process.env.FIGMA_AUTH_URL}/oauth` // TODO: Might need to add /cms here based on recent changes\n : 'https://staging.figma.com/oauth',\n refreshUrl: process.env.FIGMA_API_URL\n ? `${process.env.FIGMA_API_URL}/v1/oauth/refresh`\n : 'https://api.staging.figma.com/v1/oauth/refresh',\n tokenUrl: process.env.FIGMA_API_URL\n ? `${process.env.FIGMA_API_URL}/v1/oauth/token`\n : 'https://api.staging.figma.com/v1/oauth/token',\n },\n}\n\n/**\n * Figma OAuth2 configuration for public CLI client\n *\n * This is a PUBLIC OAuth client using PKCE (Proof Key for Code Exchange).\n * No client secret is used because CLIs cannot securely store secrets.\n * PKCE provides security through the code_verifier/code_challenge mechanism.\n *\n * For production use, register a public OAuth app with Figma.\n * To register an OAuth app, visit: https://www.figma.com/developers/api#oauth2\n */\nexport const OAUTH_CONFIG: OAuthConfig = {\n // OAuth client ID (public client)\n // Uses staging client ID by default since we use staging endpoints\n clientId: process.env.FIGMA_CLIENT_ID || FIGMA_CLIENT_IDS.staging,\n\n // No client secret - this is a public OAuth client using PKCE\n // Public clients cannot securely store secrets in CLI environments\n\n redirectUri
|
|
1
|
+
{"version":3,"sources":["../../src/config/oauth.ts"],"sourcesContent":["import type { OAuthConfig } from '../auth/types.js'\n\nimport { FIGMA_CLIENT_IDS } from '../constants.js'\n\n/**\n * Default port for OAuth callback server\n * Using a high port (34462) to avoid conflicts with common dev servers (3000, 8080, etc.)\n */\nexport const DEFAULT_CALLBACK_PORT = 34462\n\nexport const URLS: Record<\n 'prod' | 'staging',\n Pick<OAuthConfig, 'authorizationUrl' | 'refreshUrl' | 'tokenUrl'>\n> = {\n prod: {\n authorizationUrl: 'https://www.figma.com/oauth',\n refreshUrl: 'https://api.figma.com/v1/oauth/refresh',\n tokenUrl: 'https://api.figma.com/v1/oauth/token',\n },\n staging: {\n authorizationUrl: process.env.FIGMA_AUTH_URL\n ? `${process.env.FIGMA_AUTH_URL}/oauth` // TODO: Might need to add /cms here based on recent changes\n : 'https://staging.figma.com/oauth',\n refreshUrl: process.env.FIGMA_API_URL\n ? `${process.env.FIGMA_API_URL}/v1/oauth/refresh`\n : 'https://api.staging.figma.com/v1/oauth/refresh',\n tokenUrl: process.env.FIGMA_API_URL\n ? `${process.env.FIGMA_API_URL}/v1/oauth/token`\n : 'https://api.staging.figma.com/v1/oauth/token',\n },\n}\n\n/**\n * Figma OAuth2 configuration for public CLI client\n *\n * This is a PUBLIC OAuth client using PKCE (Proof Key for Code Exchange).\n * No client secret is used because CLIs cannot securely store secrets.\n * PKCE provides security through the code_verifier/code_challenge mechanism.\n *\n * For production use, register a public OAuth app with Figma.\n * To register an OAuth app, visit: https://www.figma.com/developers/api#oauth2\n */\nexport const OAUTH_CONFIG: OAuthConfig = {\n // OAuth client ID (public client)\n // Uses staging client ID by default since we use staging endpoints\n clientId: process.env.FIGMA_CLIENT_ID || FIGMA_CLIENT_IDS.staging,\n\n // No client secret - this is a public OAuth client using PKCE\n // Public clients cannot securely store secrets in CLI environments\n\n redirectUri:\n process.env.FIGMA_REDIRECT_URI || `http://localhost:${DEFAULT_CALLBACK_PORT}/callback`,\n\n // Only current_user:read scope is needed for basic user info\n scopes: ['current_user:read'],\n\n // TODO: Dynamically choose between prod and staging based on environment\n ...URLS.staging,\n}\n\n/**\n * Buffer time (in seconds) before token expiration to consider token as expired\n * This helps avoid using tokens that are about to expire\n */\nexport const TOKEN_EXPIRY_BUFFER_SECONDS = 300 // 5 minutes\n"],"names":["FIGMA_CLIENT_IDS","DEFAULT_CALLBACK_PORT","URLS","prod","authorizationUrl","refreshUrl","tokenUrl","staging","process","env","FIGMA_AUTH_URL","FIGMA_API_URL","OAUTH_CONFIG","clientId","FIGMA_CLIENT_ID","redirectUri","FIGMA_REDIRECT_URI","scopes","TOKEN_EXPIRY_BUFFER_SECONDS"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,kBAAiB;AAElD;;;CAGC,GACD,OAAO,MAAMC,wBAAwB,MAAK;AAE1C,OAAO,MAAMC,OAGT;IACFC,MAAM;QACJC,kBAAkB;QAClBC,YAAY;QACZC,UAAU;IACZ;IACAC,SAAS;QACPH,kBAAkBI,QAAQC,GAAG,CAACC,cAAc,GACxC,GAAGF,QAAQC,GAAG,CAACC,cAAc,CAAC,MAAM,CAAC,CAAC,4DAA4D;WAClG;QACJL,YAAYG,QAAQC,GAAG,CAACE,aAAa,GACjC,GAAGH,QAAQC,GAAG,CAACE,aAAa,CAAC,iBAAiB,CAAC,GAC/C;QACJL,UAAUE,QAAQC,GAAG,CAACE,aAAa,GAC/B,GAAGH,QAAQC,GAAG,CAACE,aAAa,CAAC,eAAe,CAAC,GAC7C;IACN;AACF,EAAC;AAED;;;;;;;;;CASC,GACD,OAAO,MAAMC,eAA4B;IACvC,kCAAkC;IAClC,mEAAmE;IACnEC,UAAUL,QAAQC,GAAG,CAACK,eAAe,IAAId,iBAAiBO,OAAO;IAEjE,8DAA8D;IAC9D,mEAAmE;IAEnEQ,aACEP,QAAQC,GAAG,CAACO,kBAAkB,IAAI,CAAC,iBAAiB,EAAEf,sBAAsB,SAAS,CAAC;IAExF,6DAA6D;IAC7DgB,QAAQ;QAAC;KAAoB;IAE7B,yEAAyE;IACzE,GAAGf,KAAKK,OAAO;AACjB,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMW,8BAA8B,IAAI,YAAY;CAAb"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/oauth/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,SAAS,EAAQ,MAAM,SAAS,CAAA;AAI5E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;
|
|
1
|
+
{"version":3,"file":"defaults.d.ts","sourceRoot":"","sources":["../../src/oauth/defaults.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,SAAS,EAAQ,MAAM,SAAS,CAAA;AAI5E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAKhD,eAAO,MAAM,YAAY,UAAiC,CAAA;AAE1D,eAAO,MAAM,oBAAoB,EAAE,SAQlC,CAAA;AAED,eAAO,MAAM,aAAa,iDAKrB;IACD,UAAU,EAAE,gBAAgB,CAAA;IAC5B,YAAY,EAAE,MAAM,CAAA;IACpB,aAAa,EAAE,UAAU,GAAG,SAAS,CAAA;CACtC,KAAG,cAuGH,CAAA"}
|
package/dist/oauth/defaults.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { v4 as uuid } from 'uuid';
|
|
2
2
|
import { hasUserTokenPropsChanged } from './utilities/hasUserTokenPropsChanged.js';
|
|
3
|
+
import { isDuplicateKeyError } from './utilities/isDuplicateKeyError.js';
|
|
3
4
|
export const defaultScope = [
|
|
4
5
|
'openid',
|
|
5
6
|
'profile',
|
|
@@ -60,11 +61,34 @@ export const defaultVerify = ({ collection, strategyName, usernameField })=>asyn
|
|
|
60
61
|
if (typeof collection.auth === 'object' && !collection.auth.disableLocalStrategy) {
|
|
61
62
|
newUser.password = uuid();
|
|
62
63
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
64
|
+
try {
|
|
65
|
+
user = await payload.create({
|
|
66
|
+
collection: collection.slug,
|
|
67
|
+
data: newUser,
|
|
68
|
+
depth,
|
|
69
|
+
overrideAccess: true
|
|
70
|
+
});
|
|
71
|
+
} catch (createErr) {
|
|
72
|
+
// Race condition: if unique constraint violation, user was created by concurrent request
|
|
73
|
+
if (isDuplicateKeyError(createErr)) {
|
|
74
|
+
const retryResults = await payload.find({
|
|
75
|
+
collection: collection.slug,
|
|
76
|
+
depth,
|
|
77
|
+
limit: 1,
|
|
78
|
+
pagination: false,
|
|
79
|
+
where: {
|
|
80
|
+
[usernameField.name]: {
|
|
81
|
+
equals: token[tokenUsername]
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
if (retryResults.docs.length > 0) {
|
|
86
|
+
user = retryResults.docs[0];
|
|
87
|
+
}
|
|
88
|
+
} else {
|
|
89
|
+
throw createErr;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
68
92
|
}
|
|
69
93
|
} catch (err) {
|
|
70
94
|
payload.logger.error({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/oauth/defaults.ts"],"sourcesContent":["import type { CollectionConfig, EmailField, TextField, User } from 'payload'\n\nimport { v4 as uuid } from 'uuid'\n\nimport type { VerifyFunction } from './types.js'\n\nimport { hasUserTokenPropsChanged } from './utilities/hasUserTokenPropsChanged.js'\n\nexport const defaultScope = ['openid', 'profile', 'email']\n\nexport const defaultUsernameField: TextField = {\n name: 'preferredUsername',\n type: 'text',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n unique: true,\n}\n\nexport const defaultVerify =\n ({\n collection,\n strategyName,\n usernameField,\n }: {\n collection: CollectionConfig\n strategyName: string\n usernameField: EmailField | TextField\n }): VerifyFunction =>\n async ({ payload, token }) => {\n let tokenUsername = 'preferred_username'\n\n if (usernameField.name !== 'preferredUsername') {\n tokenUsername = usernameField.name\n }\n\n if (!token[tokenUsername]) {\n return {\n user: null,\n }\n }\n\n let user: null | User = null\n const depth = typeof collection.auth === 'object' ? collection.auth.depth : undefined\n\n try {\n const results = await payload.find({\n collection: collection.slug,\n depth,\n limit: 1,\n pagination: false,\n where: {\n [usernameField.name]: { equals: token[tokenUsername] },\n },\n })\n\n if (results.docs.length > 0) {\n user = results.docs[0] as User\n // Update user with new token data\n if (hasUserTokenPropsChanged(user, token)) {\n user = (await payload.update({\n id: user.id,\n collection: collection.slug,\n data: {\n ...token,\n },\n depth,\n })) as User\n }\n } else {\n const newUser = {\n email: token.preferredUsername || token.email,\n [usernameField.name]: token[tokenUsername],\n ...token,\n }\n\n if (typeof collection.auth === 'object' && !collection.auth.disableLocalStrategy) {\n newUser.password = uuid()\n }\n\n user = (await payload.create({\n
|
|
1
|
+
{"version":3,"sources":["../../src/oauth/defaults.ts"],"sourcesContent":["import type { CollectionConfig, EmailField, TextField, User } from 'payload'\n\nimport { v4 as uuid } from 'uuid'\n\nimport type { VerifyFunction } from './types.js'\n\nimport { hasUserTokenPropsChanged } from './utilities/hasUserTokenPropsChanged.js'\nimport { isDuplicateKeyError } from './utilities/isDuplicateKeyError.js'\n\nexport const defaultScope = ['openid', 'profile', 'email']\n\nexport const defaultUsernameField: TextField = {\n name: 'preferredUsername',\n type: 'text',\n admin: {\n position: 'sidebar',\n readOnly: true,\n },\n unique: true,\n}\n\nexport const defaultVerify =\n ({\n collection,\n strategyName,\n usernameField,\n }: {\n collection: CollectionConfig\n strategyName: string\n usernameField: EmailField | TextField\n }): VerifyFunction =>\n async ({ payload, token }) => {\n let tokenUsername = 'preferred_username'\n\n if (usernameField.name !== 'preferredUsername') {\n tokenUsername = usernameField.name\n }\n\n if (!token[tokenUsername]) {\n return {\n user: null,\n }\n }\n\n let user: null | User = null\n const depth = typeof collection.auth === 'object' ? collection.auth.depth : undefined\n\n try {\n const results = await payload.find({\n collection: collection.slug,\n depth,\n limit: 1,\n pagination: false,\n where: {\n [usernameField.name]: { equals: token[tokenUsername] },\n },\n })\n\n if (results.docs.length > 0) {\n user = results.docs[0] as User\n // Update user with new token data\n if (hasUserTokenPropsChanged(user, token)) {\n user = (await payload.update({\n id: user.id,\n collection: collection.slug,\n data: {\n ...token,\n },\n depth,\n })) as User\n }\n } else {\n const newUser = {\n email: token.preferredUsername || token.email,\n [usernameField.name]: token[tokenUsername],\n ...token,\n }\n\n if (typeof collection.auth === 'object' && !collection.auth.disableLocalStrategy) {\n newUser.password = uuid()\n }\n\n try {\n user = (await payload.create({\n collection: collection.slug,\n data: newUser,\n depth,\n overrideAccess: true,\n })) as User\n } catch (createErr: unknown) {\n // Race condition: if unique constraint violation, user was created by concurrent request\n if (isDuplicateKeyError(createErr)) {\n const retryResults = await payload.find({\n collection: collection.slug,\n depth,\n limit: 1,\n pagination: false,\n where: {\n [usernameField.name]: { equals: token[tokenUsername] },\n },\n })\n\n if (retryResults.docs.length > 0) {\n user = retryResults.docs[0] as User\n }\n } else {\n throw createErr\n }\n }\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: 'Error verifying user from defaultVerify.',\n })\n return {\n user: null,\n }\n }\n\n if (user) {\n user.collection = collection.slug\n user._strategy = strategyName\n user.exp = token.exp\n\n return {\n user,\n }\n }\n\n return {\n user: null,\n }\n }\n"],"names":["v4","uuid","hasUserTokenPropsChanged","isDuplicateKeyError","defaultScope","defaultUsernameField","name","type","admin","position","readOnly","unique","defaultVerify","collection","strategyName","usernameField","payload","token","tokenUsername","user","depth","auth","undefined","results","find","slug","limit","pagination","where","equals","docs","length","update","id","data","newUser","email","preferredUsername","disableLocalStrategy","password","create","overrideAccess","createErr","retryResults","err","logger","error","msg","_strategy","exp"],"mappings":"AAEA,SAASA,MAAMC,IAAI,QAAQ,OAAM;AAIjC,SAASC,wBAAwB,QAAQ,0CAAyC;AAClF,SAASC,mBAAmB,QAAQ,qCAAoC;AAExE,OAAO,MAAMC,eAAe;IAAC;IAAU;IAAW;CAAQ,CAAA;AAE1D,OAAO,MAAMC,uBAAkC;IAC7CC,MAAM;IACNC,MAAM;IACNC,OAAO;QACLC,UAAU;QACVC,UAAU;IACZ;IACAC,QAAQ;AACV,EAAC;AAED,OAAO,MAAMC,gBACX,CAAC,EACCC,UAAU,EACVC,YAAY,EACZC,aAAa,EAKd,GACD,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAE;QACvB,IAAIC,gBAAgB;QAEpB,IAAIH,cAAcT,IAAI,KAAK,qBAAqB;YAC9CY,gBAAgBH,cAAcT,IAAI;QACpC;QAEA,IAAI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;wBAClC,MAAMC,eAAe,MAAM3B,QAAQQ,IAAI,CAAC;4BACtCX,YAAYA,WAAWY,IAAI;4BAC3BL;4BACAM,OAAO;4BACPC,YAAY;4BACZC,OAAO;gCACL,CAACb,cAAcT,IAAI,CAAC,EAAE;oCAAEuB,QAAQZ,KAAK,CAACC,cAAc;gCAAC;4BACvD;wBACF;wBAEA,IAAIyB,aAAab,IAAI,CAACC,MAAM,GAAG,GAAG;4BAChCZ,OAAOwB,aAAab,IAAI,CAAC,EAAE;wBAC7B;oBACF,OAAO;wBACL,MAAMY;oBACR;gBACF;YACF;QACF,EAAE,OAAOE,KAAc;YACrB5B,QAAQ6B,MAAM,CAACC,KAAK,CAAC;gBACnBF;gBACAG,KAAK;YACP;YACA,OAAO;gBACL5B,MAAM;YACR;QACF;QAEA,IAAIA,MAAM;YACRA,KAAKN,UAAU,GAAGA,WAAWY,IAAI;YACjCN,KAAK6B,SAAS,GAAGlC;YACjBK,KAAK8B,GAAG,GAAGhC,MAAMgC,GAAG;YAEpB,OAAO;gBACL9B;YACF;QACF;QAEA,OAAO;YACLA,MAAM;QACR;IACF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoD,MAAM,EAAE,MAAM,SAAS,CAAA;AAIvF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAc/C,eAAO,MAAM,YAAY,kBACP,aAAa,KAAG,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAoD,MAAM,EAAE,MAAM,SAAS,CAAA;AAIvF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAc/C,eAAO,MAAM,YAAY,kBACP,aAAa,KAAG,MAiR/B,CAAA"}
|
package/dist/oauth/index.js
CHANGED
|
@@ -95,7 +95,12 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
95
95
|
...existingCollection.fields,
|
|
96
96
|
{
|
|
97
97
|
name: 'email',
|
|
98
|
-
type: 'email'
|
|
98
|
+
type: 'email',
|
|
99
|
+
admin: {
|
|
100
|
+
description: 'Managed by Figma',
|
|
101
|
+
readOnly: true
|
|
102
|
+
},
|
|
103
|
+
unique: true
|
|
99
104
|
}
|
|
100
105
|
]
|
|
101
106
|
};
|
|
@@ -103,11 +108,14 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
103
108
|
collection: collectionWithEmail,
|
|
104
109
|
collectionOptions
|
|
105
110
|
});
|
|
106
|
-
// Make username field readOnly
|
|
111
|
+
// Make username field readOnly (and add description for email fields)
|
|
107
112
|
const readOnlyUsernameField = {
|
|
108
113
|
...usernameField,
|
|
109
114
|
admin: {
|
|
110
115
|
...usernameField.admin || {},
|
|
116
|
+
...usernameField.name === 'email' ? {
|
|
117
|
+
description: 'Managed by Figma'
|
|
118
|
+
} : {},
|
|
111
119
|
readOnly: true
|
|
112
120
|
}
|
|
113
121
|
};
|
|
@@ -158,6 +166,10 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
158
166
|
}
|
|
159
167
|
return {
|
|
160
168
|
...existingCollection,
|
|
169
|
+
access: {
|
|
170
|
+
...existingCollection.access || {},
|
|
171
|
+
create: ()=>false
|
|
172
|
+
},
|
|
161
173
|
auth: {
|
|
162
174
|
...typeof existingCollection.auth === 'object' ? existingCollection.auth : {},
|
|
163
175
|
disableLocalStrategy,
|
package/dist/oauth/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/oauth/index.ts"],"sourcesContent":["import type { AuthStrategy, CollectionConfig, IncomingAuthType, Plugin } from 'payload'\n\nimport { fieldAffectsData } from 'payload/shared'\n\nimport type { PluginOptions } from './types.js'\n\nimport { defaultVerify } from './defaults.js'\nimport { getLoginEndpoint } from './endpoints/getLoginEndpoint.js'\nimport { getLogoutEndpoint } from './endpoints/getLogoutEndpoint.js'\nimport { getMetaEndpoint } from './endpoints/getMetaEndpoint.js'\nimport { getRedirectToLoginEndpoint } from './endpoints/getRedirectToLoginEndpoint.js'\nimport { getAfterLogout } from './hooks/afterLogout.js'\nimport { getMeHook } from './hooks/me.js'\nimport { getRefreshHook } from './hooks/refresh.js'\nimport { Strategy } from './strategy/index.js'\nimport { getAdminCollectionSlug } from './utilities/getAdminCollectionSlug.js'\nimport { getUsernameField } from './utilities/getUsernameField.js'\n\nexport const oAuth2Plugin =\n (pluginOptions: PluginOptions): Plugin =>\n (config) => {\n const { collections: allCollectionOptions, debug, disabled } = pluginOptions\n\n const strategyName = pluginOptions?.strategyName || 'oauth'\n // Defaults to sso, but can be overridden to accommodate multiple strategies on one collection\n const endpointSlug = pluginOptions?.strategyName || 'sso'\n\n const adminCollectionSlug = getAdminCollectionSlug(config)\n const adminCollectionOptions = allCollectionOptions.find(\n ({ slug }) => slug === adminCollectionSlug,\n )\n\n if (!adminCollectionOptions) {\n throw new Error(\n `Can't find collection options for the admin collection ${adminCollectionSlug}.`,\n )\n }\n\n let LoginButton = null\n\n if (adminCollectionOptions.LoginButton === false) {\n LoginButton = null\n } else if (typeof adminCollectionOptions.LoginButton === 'string') {\n LoginButton = {\n clientProps: {\n disabled,\n endpointSlug,\n },\n path: adminCollectionOptions.LoginButton,\n }\n } else if (typeof adminCollectionOptions.LoginButton === 'object') {\n LoginButton = {\n ...adminCollectionOptions.LoginButton,\n clientProps: {\n ...adminCollectionOptions.LoginButton.clientProps,\n disabled,\n endpointSlug,\n },\n }\n } else {\n // Default to the provided LoginButton component path\n LoginButton = {\n clientProps: {\n disabled,\n endpointSlug,\n },\n path: '@payloadcms/figma/client#DefaultLoginButton',\n }\n }\n\n return {\n ...config,\n admin: {\n ...(config.admin || {}),\n components: {\n ...(typeof config.admin === 'object' && typeof config.admin.components === 'object'\n ? config.admin.components\n : {}),\n ...(adminCollectionOptions.endOAuthSessionOnLogout\n ? {\n logout: {\n Button: {\n clientProps: {\n disabled,\n endpointSlug,\n },\n path: '@payloadcms/figma/client#LogoutButton',\n },\n },\n }\n : {}),\n beforeLogin: [\n ...(typeof config.admin === 'object' &&\n typeof config.admin.components === 'object' &&\n Array.isArray(config.admin.components.beforeLogin)\n ? config.admin.components.beforeLogin\n : []),\n ...(LoginButton ? [LoginButton] : []),\n ],\n },\n },\n collections: (config.collections || []).map((existingCollection) => {\n const collectionOptions = allCollectionOptions.find(\n ({ slug }) => slug === existingCollection.slug,\n )\n\n if (!collectionOptions) {\n return existingCollection\n }\n\n let cookieName = pluginOptions?.cookieName || `payload-${strategyName}-token`\n // If the usePayloadJWT option is enabled, use the default cookie name from Payload\n if (collectionOptions.usePayloadJWT) {\n cookieName = `${config.cookiePrefix || 'payload'}-token`\n }\n\n // Check if email field exists, if not add it\n const hasEmailField = existingCollection.fields.some(\n (field) => 'name' in field && field.name === 'email',\n )\n\n // Add email field to collection before getting username field\n // This ensures getUsernameField can find the email field if it's configured as the username\n const collectionWithEmail: CollectionConfig = hasEmailField\n ? existingCollection\n : {\n ...existingCollection,\n fields: [\n ...existingCollection.fields,\n {\n name: 'email',\n type: 'email',\n },\n ],\n }\n\n const usernameField = getUsernameField({\n collection: collectionWithEmail,\n collectionOptions,\n })\n\n // Make username field readOnly\n const readOnlyUsernameField = {\n ...usernameField,\n admin: {\n ...(usernameField.admin || {}),\n readOnly: true,\n },\n } as typeof usernameField\n\n const isUsernameFieldString = typeof adminCollectionOptions.usernameField === 'string'\n\n const fields = [\n ...collectionWithEmail.fields.map((field) =>\n fieldAffectsData(field) && field.name === usernameField.name\n ? readOnlyUsernameField\n : field,\n ),\n ...(isUsernameFieldString ? [] : [readOnlyUsernameField]),\n ]\n\n if (disabled) {\n return {\n ...existingCollection,\n fields,\n }\n }\n\n const strategy = new Strategy({\n clientID: collectionOptions.clientID,\n clientSecret: collectionOptions.clientSecret,\n collection: existingCollection,\n collectionOptions,\n cookieName,\n debug,\n identityMetadata: collectionOptions.identityMetadata,\n pluginOptions,\n strategyName,\n verify:\n collectionOptions.verify ??\n defaultVerify({\n collection: existingCollection,\n strategyName,\n usernameField,\n }),\n })\n\n const authStrategy: AuthStrategy = {\n name: `${existingCollection.slug}-${strategyName}`,\n // Bind 'this' to ensure the authenticate function has the correct context\n authenticate: strategy.authenticate.bind(strategy),\n }\n\n let disableLocalStrategy: IncomingAuthType['disableLocalStrategy']\n\n if (collectionOptions.disableLocalStrategy === false) {\n // When the plugin collection option has disableLocalStrategy option set to false, do not disable the local strategy\n disableLocalStrategy = undefined\n } else if (collectionOptions.disableLocalStrategy) {\n // use the configured disableLocalStrategy which can include `enableFields`, etc.\n disableLocalStrategy = collectionOptions.disableLocalStrategy\n } else {\n // by default disableLocalStrategy\n disableLocalStrategy = true\n }\n\n return {\n ...existingCollection,\n auth: {\n ...(typeof existingCollection.auth === 'object' ? existingCollection.auth : {}),\n disableLocalStrategy,\n strategies: [\n ...(typeof existingCollection.auth === 'object' &&\n Array.isArray(existingCollection.auth.strategies)\n ? existingCollection.auth.strategies\n : []),\n authStrategy,\n ],\n },\n endpoints: [\n ...(existingCollection.endpoints || []),\n getLoginEndpoint({\n collection: existingCollection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n getMetaEndpoint({\n collection: existingCollection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n getLogoutEndpoint({\n collection: existingCollection,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n getRedirectToLoginEndpoint({\n collection: existingCollection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n ],\n fields,\n hooks: {\n ...(existingCollection.hooks || {}),\n afterLogout: [\n ...(typeof existingCollection.hooks === 'object' &&\n Array.isArray(existingCollection.hooks.afterLogout)\n ? existingCollection.hooks.afterLogout\n : []),\n getAfterLogout({\n collection: existingCollection,\n cookieName,\n pluginOptions,\n }),\n ],\n me: [\n ...(typeof existingCollection.hooks === 'object' &&\n Array.isArray(existingCollection.hooks.me)\n ? existingCollection.hooks.me\n : []),\n // Do not inject the me hook if the usePayloadJWT option is enabled\n ...(!collectionOptions.usePayloadJWT ? [getMeHook({ cookieName })] : []),\n ],\n refresh: [\n ...(typeof existingCollection.hooks === 'object' &&\n Array.isArray(existingCollection.hooks.refresh)\n ? existingCollection.hooks.refresh\n : []),\n getRefreshHook({ pluginOptions, strategy }),\n ],\n },\n }\n }),\n }\n }\n"],"names":["fieldAffectsData","defaultVerify","getLoginEndpoint","getLogoutEndpoint","getMetaEndpoint","getRedirectToLoginEndpoint","getAfterLogout","getMeHook","getRefreshHook","Strategy","getAdminCollectionSlug","getUsernameField","oAuth2Plugin","pluginOptions","config","collections","allCollectionOptions","debug","disabled","strategyName","endpointSlug","adminCollectionSlug","adminCollectionOptions","find","slug","Error","LoginButton","clientProps","path","admin","components","endOAuthSessionOnLogout","logout","Button","beforeLogin","Array","isArray","map","existingCollection","collectionOptions","cookieName","usePayloadJWT","cookiePrefix","hasEmailField","fields","some","field","name","collectionWithEmail","type","usernameField","collection","readOnlyUsernameField","readOnly","isUsernameFieldString","strategy","clientID","clientSecret","identityMetadata","verify","authStrategy","authenticate","bind","disableLocalStrategy","undefined","auth","strategies","endpoints","hooks","afterLogout","me","refresh"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,iBAAgB;AAIjD,SAASC,aAAa,QAAQ,gBAAe;AAC7C,SAASC,gBAAgB,QAAQ,kCAAiC;AAClE,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,eAAe,QAAQ,iCAAgC;AAChE,SAASC,0BAA0B,QAAQ,4CAA2C;AACtF,SAASC,cAAc,QAAQ,yBAAwB;AACvD,SAASC,SAAS,QAAQ,gBAAe;AACzC,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,QAAQ,QAAQ,sBAAqB;AAC9C,SAASC,sBAAsB,QAAQ,wCAAuC;AAC9E,SAASC,gBAAgB,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CAACG,OAAO,GAChC,EAAE;4BACN/D,eAAe;gCAAEK;gCAAe0C;4BAAS;yBAC1C;oBACH;gBACF;YACF;QACF;IACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/oauth/index.ts"],"sourcesContent":["import type { AuthStrategy, CollectionConfig, IncomingAuthType, Plugin } from 'payload'\n\nimport { fieldAffectsData } from 'payload/shared'\n\nimport type { PluginOptions } from './types.js'\n\nimport { defaultVerify } from './defaults.js'\nimport { getLoginEndpoint } from './endpoints/getLoginEndpoint.js'\nimport { getLogoutEndpoint } from './endpoints/getLogoutEndpoint.js'\nimport { getMetaEndpoint } from './endpoints/getMetaEndpoint.js'\nimport { getRedirectToLoginEndpoint } from './endpoints/getRedirectToLoginEndpoint.js'\nimport { getAfterLogout } from './hooks/afterLogout.js'\nimport { getMeHook } from './hooks/me.js'\nimport { getRefreshHook } from './hooks/refresh.js'\nimport { Strategy } from './strategy/index.js'\nimport { getAdminCollectionSlug } from './utilities/getAdminCollectionSlug.js'\nimport { getUsernameField } from './utilities/getUsernameField.js'\n\nexport const oAuth2Plugin =\n (pluginOptions: PluginOptions): Plugin =>\n (config) => {\n const { collections: allCollectionOptions, debug, disabled } = pluginOptions\n\n const strategyName = pluginOptions?.strategyName || 'oauth'\n // Defaults to sso, but can be overridden to accommodate multiple strategies on one collection\n const endpointSlug = pluginOptions?.strategyName || 'sso'\n\n const adminCollectionSlug = getAdminCollectionSlug(config)\n const adminCollectionOptions = allCollectionOptions.find(\n ({ slug }) => slug === adminCollectionSlug,\n )\n\n if (!adminCollectionOptions) {\n throw new Error(\n `Can't find collection options for the admin collection ${adminCollectionSlug}.`,\n )\n }\n\n let LoginButton = null\n\n if (adminCollectionOptions.LoginButton === false) {\n LoginButton = null\n } else if (typeof adminCollectionOptions.LoginButton === 'string') {\n LoginButton = {\n clientProps: {\n disabled,\n endpointSlug,\n },\n path: adminCollectionOptions.LoginButton,\n }\n } else if (typeof adminCollectionOptions.LoginButton === 'object') {\n LoginButton = {\n ...adminCollectionOptions.LoginButton,\n clientProps: {\n ...adminCollectionOptions.LoginButton.clientProps,\n disabled,\n endpointSlug,\n },\n }\n } else {\n // Default to the provided LoginButton component path\n LoginButton = {\n clientProps: {\n disabled,\n endpointSlug,\n },\n path: '@payloadcms/figma/client#DefaultLoginButton',\n }\n }\n\n return {\n ...config,\n admin: {\n ...(config.admin || {}),\n components: {\n ...(typeof config.admin === 'object' && typeof config.admin.components === 'object'\n ? config.admin.components\n : {}),\n ...(adminCollectionOptions.endOAuthSessionOnLogout\n ? {\n logout: {\n Button: {\n clientProps: {\n disabled,\n endpointSlug,\n },\n path: '@payloadcms/figma/client#LogoutButton',\n },\n },\n }\n : {}),\n beforeLogin: [\n ...(typeof config.admin === 'object' &&\n typeof config.admin.components === 'object' &&\n Array.isArray(config.admin.components.beforeLogin)\n ? config.admin.components.beforeLogin\n : []),\n ...(LoginButton ? [LoginButton] : []),\n ],\n },\n },\n collections: (config.collections || []).map((existingCollection) => {\n const collectionOptions = allCollectionOptions.find(\n ({ slug }) => slug === existingCollection.slug,\n )\n\n if (!collectionOptions) {\n return existingCollection\n }\n\n let cookieName = pluginOptions?.cookieName || `payload-${strategyName}-token`\n // If the usePayloadJWT option is enabled, use the default cookie name from Payload\n if (collectionOptions.usePayloadJWT) {\n cookieName = `${config.cookiePrefix || 'payload'}-token`\n }\n\n // Check if email field exists, if not add it\n const hasEmailField = existingCollection.fields.some(\n (field) => 'name' in field && field.name === 'email',\n )\n\n // Add email field to collection before getting username field\n // This ensures getUsernameField can find the email field if it's configured as the username\n const collectionWithEmail: CollectionConfig = hasEmailField\n ? existingCollection\n : {\n ...existingCollection,\n fields: [\n ...existingCollection.fields,\n {\n name: 'email',\n type: 'email',\n admin: {\n description: 'Managed by Figma',\n readOnly: true,\n },\n unique: true,\n },\n ],\n }\n\n const usernameField = getUsernameField({\n collection: collectionWithEmail,\n collectionOptions,\n })\n\n // Make username field readOnly (and add description for email fields)\n const readOnlyUsernameField = {\n ...usernameField,\n admin: {\n ...(usernameField.admin || {}),\n ...(usernameField.name === 'email' ? { description: 'Managed by Figma' } : {}),\n readOnly: true,\n },\n } as typeof usernameField\n\n const isUsernameFieldString = typeof adminCollectionOptions.usernameField === 'string'\n\n const fields = [\n ...collectionWithEmail.fields.map((field) =>\n fieldAffectsData(field) && field.name === usernameField.name\n ? readOnlyUsernameField\n : field,\n ),\n ...(isUsernameFieldString ? [] : [readOnlyUsernameField]),\n ]\n\n if (disabled) {\n return {\n ...existingCollection,\n fields,\n }\n }\n\n const strategy = new Strategy({\n clientID: collectionOptions.clientID,\n clientSecret: collectionOptions.clientSecret,\n collection: existingCollection,\n collectionOptions,\n cookieName,\n debug,\n identityMetadata: collectionOptions.identityMetadata,\n pluginOptions,\n strategyName,\n verify:\n collectionOptions.verify ??\n defaultVerify({\n collection: existingCollection,\n strategyName,\n usernameField,\n }),\n })\n\n const authStrategy: AuthStrategy = {\n name: `${existingCollection.slug}-${strategyName}`,\n // Bind 'this' to ensure the authenticate function has the correct context\n authenticate: strategy.authenticate.bind(strategy),\n }\n\n let disableLocalStrategy: IncomingAuthType['disableLocalStrategy']\n\n if (collectionOptions.disableLocalStrategy === false) {\n // When the plugin collection option has disableLocalStrategy option set to false, do not disable the local strategy\n disableLocalStrategy = undefined\n } else if (collectionOptions.disableLocalStrategy) {\n // use the configured disableLocalStrategy which can include `enableFields`, etc.\n disableLocalStrategy = collectionOptions.disableLocalStrategy\n } else {\n // by default disableLocalStrategy\n disableLocalStrategy = true\n }\n\n return {\n ...existingCollection,\n access: {\n ...(existingCollection.access || {}),\n create: () => false,\n },\n auth: {\n ...(typeof existingCollection.auth === 'object' ? existingCollection.auth : {}),\n disableLocalStrategy,\n strategies: [\n ...(typeof existingCollection.auth === 'object' &&\n Array.isArray(existingCollection.auth.strategies)\n ? existingCollection.auth.strategies\n : []),\n authStrategy,\n ],\n },\n endpoints: [\n ...(existingCollection.endpoints || []),\n getLoginEndpoint({\n collection: existingCollection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n getMetaEndpoint({\n collection: existingCollection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n getLogoutEndpoint({\n collection: existingCollection,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n getRedirectToLoginEndpoint({\n collection: existingCollection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n }),\n ],\n fields,\n hooks: {\n ...(existingCollection.hooks || {}),\n afterLogout: [\n ...(typeof existingCollection.hooks === 'object' &&\n Array.isArray(existingCollection.hooks.afterLogout)\n ? existingCollection.hooks.afterLogout\n : []),\n getAfterLogout({\n collection: existingCollection,\n cookieName,\n pluginOptions,\n }),\n ],\n me: [\n ...(typeof existingCollection.hooks === 'object' &&\n Array.isArray(existingCollection.hooks.me)\n ? existingCollection.hooks.me\n : []),\n // Do not inject the me hook if the usePayloadJWT option is enabled\n ...(!collectionOptions.usePayloadJWT ? [getMeHook({ cookieName })] : []),\n ],\n refresh: [\n ...(typeof existingCollection.hooks === 'object' &&\n Array.isArray(existingCollection.hooks.refresh)\n ? existingCollection.hooks.refresh\n : []),\n getRefreshHook({ pluginOptions, strategy }),\n ],\n },\n }\n }),\n }\n }\n"],"names":["fieldAffectsData","defaultVerify","getLoginEndpoint","getLogoutEndpoint","getMetaEndpoint","getRedirectToLoginEndpoint","getAfterLogout","getMeHook","getRefreshHook","Strategy","getAdminCollectionSlug","getUsernameField","oAuth2Plugin","pluginOptions","config","collections","allCollectionOptions","debug","disabled","strategyName","endpointSlug","adminCollectionSlug","adminCollectionOptions","find","slug","Error","LoginButton","clientProps","path","admin","components","endOAuthSessionOnLogout","logout","Button","beforeLogin","Array","isArray","map","existingCollection","collectionOptions","cookieName","usePayloadJWT","cookiePrefix","hasEmailField","fields","some","field","name","collectionWithEmail","type","description","readOnly","unique","usernameField","collection","readOnlyUsernameField","isUsernameFieldString","strategy","clientID","clientSecret","identityMetadata","verify","authStrategy","authenticate","bind","disableLocalStrategy","undefined","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F;qBACD;oBACDb;oBACA4B,OAAO;wBACL,GAAIlC,mBAAmBkC,KAAK,IAAI,CAAC,CAAC;wBAClCC,aAAa;+BACP,OAAOnC,mBAAmBkC,KAAK,KAAK,YACxCrC,MAAMC,OAAO,CAACE,mBAAmBkC,KAAK,CAACC,WAAW,IAC9CnC,mBAAmBkC,KAAK,CAACC,WAAW,GACpC,EAAE;4BACNnE,eAAe;gCACbgD,YAAYhB;gCACZE;gCACA3B;4BACF;yBACD;wBACD6D,IAAI;+BACE,OAAOpC,mBAAmBkC,KAAK,KAAK,YACxCrC,MAAMC,OAAO,CAACE,mBAAmBkC,KAAK,CAACE,EAAE,IACrCpC,mBAAmBkC,KAAK,CAACE,EAAE,GAC3B,EAAE;4BACN,mEAAmE;+BAC/D,CAACnC,kBAAkBE,aAAa,GAAG;gCAAClC,UAAU;oCAAEiC;gCAAW;6BAAG,GAAG,EAAE;yBACxE;wBACDmC,SAAS;+BACH,OAAOrC,mBAAmBkC,KAAK,KAAK,YACxCrC,MAAMC,OAAO,CAACE,mBAAmBkC,KAAK,CAACG,OAAO,IAC1CrC,mBAAmBkC,KAAK,CAACG,OAAO,GAChC,EAAE;4BACNnE,eAAe;gCAAEK;gCAAe4C;4BAAS;yBAC1C;oBACH;gBACF;YACF;QACF;IACF,EAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as jose from 'jose';
|
|
2
2
|
import { APIError, parseCookies } from 'payload';
|
|
3
|
-
import { validateProjectToken } from '../../auth/jwt-validator.js';
|
|
3
|
+
import { JWTValidationError, validateProjectToken } from '../../auth/jwt-validator.js';
|
|
4
4
|
import { getEnvironment } from '../../constants.js';
|
|
5
5
|
import { createDebugLogger } from '../utilities/createDebugLogger.js';
|
|
6
6
|
import { getTokenExp } from '../utilities/getTokenExp.js';
|
|
@@ -136,7 +136,7 @@ export class Strategy {
|
|
|
136
136
|
});
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
|
-
if (oauthTokenVerifyResult instanceof
|
|
139
|
+
if (oauthTokenVerifyResult instanceof JWTValidationError && oauthTokenVerifyResult.code === 'EXPIRED' && refreshToken && !this.collectionOptions.usePayloadJWT && canSetHeaders) {
|
|
140
140
|
const refreshed = await refreshTokens({
|
|
141
141
|
payload,
|
|
142
142
|
refreshToken,
|
|
@@ -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 { 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 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\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","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","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,oBAAoB,QAAQ,8BAA6B;AAClE,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,GAAG,KAAKA,KAAK;gBACtC;YACF;YAEA,MAAMQ,YAAY,MAAM5F,KAAK6F,SAAS,CAACF,KAAKN;YAC5C,IAAI,CAAEO,CAAAA,qBAAqBE,SAAQ,GAAI;gBACrC,MAAM,IAAIpC,MAAM;YAClB;YAEA+B,SAAS,MAAMzF,KAAK+F,UAAU,CAACH;YAC/BF,WAAW;YAEX;QACF;QAEA,IAAI,CAACA,UAAU;YACb,MAAM,IAAIhC,MAAM;QAClB;QAEA,IAAI,CAAC+B,QAAQ;YACX,MAAM,IAAI/B,MAAM;QAClB;QAEA,OAAO+B;IACT;IAEA,MAAMhC,UAAU,EAAEpB,OAAO,EAAEe,KAAK,EAAiB,EAA0C;QACzF,IAAI;YACF,MAAM4C,WAAW,MAAM7F,qBAAqBiD,OAAOhD;YACnD,IAAI,OAAO4F,aAAa,UAAU;gBAChC,OAAOA;YACT;QACF,EAAE,OAAOC,KAAc;YACrB5D,QAAQ6D,MAAM,CAACvB,KAAK,CAAC;gBACnBsB;gBACArD,KAAK;YACP;YAEA,IAAIqD,eAAevC,OAAO;gBACxB,OAAOuC;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 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 JWTValidationError &&\n oauthTokenVerifyResult.code === 'EXPIRED' &&\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\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","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","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;AAe7D,OAAO,MAAMC;IACXC,SAAgB;IAChBC,aAAqB;IACrBC,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,CAACJ,QAAQ,GAAGgB,QAAQhB,QAAQ;QAChC,IAAI,CAACC,YAAY,GAAGe,QAAQf,YAAY;QACxC,IAAI,CA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,OAAO;gBACxB,OAAOwC;YACT;YACA,OAAO;QACT;QACA,OAAO;IACT;AACF"}
|
package/dist/oauth/types.d.ts
CHANGED
|
@@ -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,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,gBAAgB,EAChB,OAAO,EACP,cAAc,EACd,SAAS,EACV,MAAM,SAAS,CAAA;AAEhB,MAAM,MAAM,IAAI,GAAG,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;AAEnE,MAAM,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE;IAClC,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE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ANGED
|
@@ -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?: 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 *
|
|
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"}
|
|
@@ -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"}
|