@payloadcms/figma 0.0.1-alpha.38-2 → 0.0.1-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/control-plane.d.ts +1 -22
- package/dist/api/control-plane.d.ts.map +1 -1
- package/dist/api/control-plane.js +22 -55
- package/dist/api/control-plane.js.map +1 -1
- package/dist/api/figma-api.d.ts.map +1 -1
- package/dist/api/figma-api.js +26 -45
- package/dist/api/figma-api.js.map +1 -1
- package/dist/auth/callback-server.d.ts.map +1 -1
- package/dist/auth/callback-server.js +1 -2
- package/dist/auth/callback-server.js.map +1 -1
- package/dist/auth/crypto-utils.d.ts.map +1 -1
- package/dist/auth/crypto-utils.js +5 -5
- package/dist/auth/crypto-utils.js.map +1 -1
- package/dist/auth/jwt-validator.d.ts +1 -2
- package/dist/auth/jwt-validator.d.ts.map +1 -1
- package/dist/auth/jwt-validator.js +2 -2
- package/dist/auth/jwt-validator.js.map +1 -1
- package/dist/auth/oauth-flow.d.ts +1 -1
- package/dist/auth/oauth-flow.d.ts.map +1 -1
- package/dist/auth/oauth-flow.js +8 -9
- package/dist/auth/oauth-flow.js.map +1 -1
- package/dist/auth/project-token.d.ts.map +1 -1
- package/dist/auth/project-token.js +4 -9
- package/dist/auth/project-token.js.map +1 -1
- package/dist/auth/refresh.d.ts.map +1 -1
- package/dist/auth/refresh.js +9 -14
- package/dist/auth/refresh.js.map +1 -1
- package/dist/auth/token-store.d.ts +0 -10
- package/dist/auth/token-store.d.ts.map +1 -1
- package/dist/auth/token-store.js +0 -20
- package/dist/auth/token-store.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +0 -22
- package/dist/cli.js.map +1 -1
- package/dist/commands/deploy.d.ts +0 -4
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +129 -71
- package/dist/commands/deploy.js.map +1 -1
- package/dist/commands/init.d.ts +5 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +85 -90
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/list-tokens.d.ts.map +1 -1
- package/dist/commands/list-tokens.js +3 -6
- package/dist/commands/list-tokens.js.map +1 -1
- package/dist/commands/login.d.ts +1 -8
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +11 -21
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/logout.js +2 -2
- package/dist/commands/logout.js.map +1 -1
- package/dist/config/oauth.d.ts +14 -4
- package/dist/config/oauth.d.ts.map +1 -1
- package/dist/config/oauth.js +40 -19
- package/dist/config/oauth.js.map +1 -1
- package/dist/constants.d.ts +18 -26
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +20 -34
- package/dist/constants.js.map +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -3
- package/dist/index.js.map +1 -1
- package/dist/oauth/components/LoginButton/index.d.ts.map +1 -1
- package/dist/oauth/components/LoginButton/index.js +6 -50
- package/dist/oauth/components/LoginButton/index.js.map +1 -1
- package/dist/oauth/components/LoginButton/index.scss +3 -50
- package/dist/oauth/components/LogoutButton/index.d.ts.map +1 -1
- package/dist/oauth/components/LogoutButton/index.js +1 -0
- package/dist/oauth/components/LogoutButton/index.js.map +1 -1
- package/dist/oauth/defaults.d.ts.map +1 -1
- package/dist/oauth/defaults.js +5 -29
- package/dist/oauth/defaults.js.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.d.ts.map +1 -1
- package/dist/oauth/endpoints/getLoginEndpoint.js +4 -4
- package/dist/oauth/endpoints/getLoginEndpoint.js.map +1 -1
- package/dist/oauth/index.d.ts.map +1 -1
- package/dist/oauth/index.js +7 -42
- package/dist/oauth/index.js.map +1 -1
- package/dist/oauth/strategy/index.d.ts +2 -0
- package/dist/oauth/strategy/index.d.ts.map +1 -1
- package/dist/oauth/strategy/index.js +15 -38
- package/dist/oauth/strategy/index.js.map +1 -1
- package/dist/oauth/types.d.ts +6 -6
- package/dist/oauth/types.d.ts.map +1 -1
- package/dist/oauth/types.js.map +1 -1
- package/dist/oauth/utilities/createCookieOptions.d.ts.map +1 -1
- package/dist/oauth/utilities/createCookieOptions.js.map +1 -1
- package/dist/oauth/utilities/refreshTokens.d.ts.map +1 -1
- package/dist/oauth/utilities/refreshTokens.js +1 -1
- package/dist/oauth/utilities/refreshTokens.js.map +1 -1
- package/dist/plugin/build-config.d.ts +4 -21
- package/dist/plugin/build-config.d.ts.map +1 -1
- package/dist/plugin/build-config.js +8 -114
- package/dist/plugin/build-config.js.map +1 -1
- package/dist/types.d.ts +0 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/asset-collection.d.ts +6 -3
- package/dist/utils/asset-collection.d.ts.map +1 -1
- package/dist/utils/asset-collection.js +34 -10
- package/dist/utils/asset-collection.js.map +1 -1
- package/dist/utils/config.js +1 -1
- package/dist/utils/config.js.map +1 -1
- package/dist/utils/env-management.d.ts +8 -9
- package/dist/utils/env-management.d.ts.map +1 -1
- package/dist/utils/env-management.js +74 -73
- package/dist/utils/env-management.js.map +1 -1
- package/dist/utils/formatter.d.ts.map +1 -1
- package/dist/utils/formatter.js +5 -3
- package/dist/utils/formatter.js.map +1 -1
- package/dist/utils/lambda-config.d.ts +1 -3
- package/dist/utils/lambda-config.d.ts.map +1 -1
- package/dist/utils/lambda-config.js +21 -13
- package/dist/utils/lambda-config.js.map +1 -1
- package/dist/utils/messages.js +7 -7
- package/dist/utils/messages.js.map +1 -1
- package/dist/utils/payload-config-ast.d.ts +3 -22
- package/dist/utils/payload-config-ast.d.ts.map +1 -1
- package/dist/utils/payload-config-ast.js +31 -89
- package/dist/utils/payload-config-ast.js.map +1 -1
- package/dist/utils/payload-config-finder.d.ts +2 -2
- package/dist/utils/payload-config-finder.d.ts.map +1 -1
- package/dist/utils/payload-config-finder.js +9 -48
- package/dist/utils/payload-config-finder.js.map +1 -1
- package/dist/utils/payload-config-modifier.d.ts.map +1 -1
- package/dist/utils/payload-config-modifier.js +6 -54
- package/dist/utils/payload-config-modifier.js.map +1 -1
- package/dist/utils/payload-package-check.d.ts +1 -12
- package/dist/utils/payload-package-check.d.ts.map +1 -1
- package/dist/utils/payload-package-check.js +5 -63
- package/dist/utils/payload-package-check.js.map +1 -1
- package/dist/utils/project.d.ts.map +1 -1
- package/dist/utils/project.js +5 -8
- package/dist/utils/project.js.map +1 -1
- package/dist/utils/s3-upload.d.ts +1 -0
- package/dist/utils/s3-upload.d.ts.map +1 -1
- package/dist/utils/s3-upload.js +3 -10
- package/dist/utils/s3-upload.js.map +1 -1
- package/dist/utils/token-display.d.ts.map +1 -1
- package/dist/utils/token-display.js +5 -11
- package/dist/utils/token-display.js.map +1 -1
- package/dist/utils/typescript-validator.d.ts.map +1 -1
- package/dist/utils/typescript-validator.js +6 -4
- package/dist/utils/typescript-validator.js.map +1 -1
- package/package.json +7 -31
- package/dist/commands/build-lambda-zip.d.ts +0 -5
- package/dist/commands/build-lambda-zip.d.ts.map +0 -1
- package/dist/commands/build-lambda-zip.js +0 -19
- package/dist/commands/build-lambda-zip.js.map +0 -1
- package/dist/db-content-api/README.md +0 -98
- package/dist/db-content-api/generated/content-api-types.d.ts +0 -3848
- package/dist/db-content-api/generated/content-api-types.d.ts.map +0 -1
- package/dist/db-content-api/generated/content-api-types.js +0 -7
- package/dist/db-content-api/generated/content-api-types.js.map +0 -1
- package/dist/db-content-api/index.d.ts +0 -18
- package/dist/db-content-api/index.d.ts.map +0 -1
- package/dist/db-content-api/index.js +0 -571
- package/dist/db-content-api/index.js.map +0 -1
- package/dist/db-content-api/temp-utilities/pagination.d.ts +0 -13
- package/dist/db-content-api/temp-utilities/pagination.d.ts.map +0 -1
- package/dist/db-content-api/temp-utilities/pagination.js +0 -45
- package/dist/db-content-api/temp-utilities/pagination.js.map +0 -1
- package/dist/db-content-api/temp-utilities/slug.d.ts +0 -2
- package/dist/db-content-api/temp-utilities/slug.d.ts.map +0 -1
- package/dist/db-content-api/temp-utilities/slug.js +0 -3
- package/dist/db-content-api/temp-utilities/slug.js.map +0 -1
- package/dist/db-content-api/temp-utilities/sorting.d.ts +0 -3
- package/dist/db-content-api/temp-utilities/sorting.d.ts.map +0 -1
- package/dist/db-content-api/temp-utilities/sorting.js +0 -32
- package/dist/db-content-api/temp-utilities/sorting.js.map +0 -1
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts +0 -4
- package/dist/db-content-api/temp-utilities/unwrapDocument.d.ts.map +0 -1
- package/dist/db-content-api/temp-utilities/unwrapDocument.js +0 -53
- package/dist/db-content-api/temp-utilities/unwrapDocument.js.map +0 -1
- package/dist/db-content-api/utilities/auth.d.ts +0 -30
- package/dist/db-content-api/utilities/auth.d.ts.map +0 -1
- package/dist/db-content-api/utilities/auth.js +0 -81
- package/dist/db-content-api/utilities/auth.js.map +0 -1
- package/dist/db-content-api/utilities/data/applyDefaults.d.ts +0 -7
- package/dist/db-content-api/utilities/data/applyDefaults.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data/applyDefaults.js +0 -59
- package/dist/db-content-api/utilities/data/applyDefaults.js.map +0 -1
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts +0 -11
- package/dist/db-content-api/utilities/data/castFieldValue.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data/castFieldValue.js +0 -66
- package/dist/db-content-api/utilities/data/castFieldValue.js.map +0 -1
- package/dist/db-content-api/utilities/data/index.d.ts +0 -30
- package/dist/db-content-api/utilities/data/index.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data/index.js +0 -173
- package/dist/db-content-api/utilities/data/index.js.map +0 -1
- package/dist/db-content-api/utilities/data/removeVirtualFields.d.ts +0 -12
- package/dist/db-content-api/utilities/data/removeVirtualFields.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data/removeVirtualFields.js +0 -54
- package/dist/db-content-api/utilities/data/removeVirtualFields.js.map +0 -1
- package/dist/db-content-api/utilities/data/stripFields.d.ts +0 -48
- package/dist/db-content-api/utilities/data/stripFields.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data/stripFields.js +0 -195
- package/dist/db-content-api/utilities/data/stripFields.js.map +0 -1
- package/dist/db-content-api/utilities/joins.d.ts +0 -55
- package/dist/db-content-api/utilities/joins.d.ts.map +0 -1
- package/dist/db-content-api/utilities/joins.js +0 -136
- package/dist/db-content-api/utilities/joins.js.map +0 -1
- package/dist/db-content-api/utilities/where.d.ts +0 -12
- package/dist/db-content-api/utilities/where.d.ts.map +0 -1
- package/dist/db-content-api/utilities/where.js +0 -107
- package/dist/db-content-api/utilities/where.js.map +0 -1
- package/dist/endpoints/health.d.ts +0 -3
- package/dist/endpoints/health.d.ts.map +0 -1
- package/dist/endpoints/health.js +0 -11
- package/dist/endpoints/health.js.map +0 -1
- package/dist/exports/client.d.ts +0 -4
- package/dist/exports/client.d.ts.map +0 -1
- package/dist/exports/client.js +0 -5
- package/dist/exports/client.js.map +0 -1
- package/dist/oauth/utilities/isDuplicateKeyError.d.ts +0 -7
- package/dist/oauth/utilities/isDuplicateKeyError.d.ts.map +0 -1
- package/dist/oauth/utilities/isDuplicateKeyError.js +0 -14
- package/dist/oauth/utilities/isDuplicateKeyError.js.map +0 -1
- package/dist/storage-content-api/api-types.d.ts +0 -161
- package/dist/storage-content-api/api-types.d.ts.map +0 -1
- package/dist/storage-content-api/api-types.js +0 -6
- package/dist/storage-content-api/api-types.js.map +0 -1
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts +0 -9
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.d.ts.map +0 -1
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js +0 -42
- package/dist/storage-content-api/client-uploads/ClientUploadHandler.js.map +0 -1
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts +0 -13
- package/dist/storage-content-api/client-uploads/generateSignedURL.d.ts.map +0 -1
- package/dist/storage-content-api/client-uploads/generateSignedURL.js +0 -31
- package/dist/storage-content-api/client-uploads/generateSignedURL.js.map +0 -1
- package/dist/storage-content-api/client.d.ts +0 -6
- package/dist/storage-content-api/client.d.ts.map +0 -1
- package/dist/storage-content-api/client.js +0 -36
- package/dist/storage-content-api/client.js.map +0 -1
- package/dist/storage-content-api/generateURL.d.ts +0 -7
- package/dist/storage-content-api/generateURL.d.ts.map +0 -1
- package/dist/storage-content-api/generateURL.js +0 -7
- package/dist/storage-content-api/generateURL.js.map +0 -1
- package/dist/storage-content-api/handleDelete.d.ts +0 -8
- package/dist/storage-content-api/handleDelete.d.ts.map +0 -1
- package/dist/storage-content-api/handleDelete.js +0 -15
- package/dist/storage-content-api/handleDelete.js.map +0 -1
- package/dist/storage-content-api/handleUpload.d.ts +0 -11
- package/dist/storage-content-api/handleUpload.d.ts.map +0 -1
- package/dist/storage-content-api/handleUpload.js +0 -136
- package/dist/storage-content-api/handleUpload.js.map +0 -1
- package/dist/storage-content-api/index.d.ts +0 -5
- package/dist/storage-content-api/index.d.ts.map +0 -1
- package/dist/storage-content-api/index.js +0 -31
- package/dist/storage-content-api/index.js.map +0 -1
- package/dist/storage-content-api/staticHandler.d.ts +0 -10
- package/dist/storage-content-api/staticHandler.d.ts.map +0 -1
- package/dist/storage-content-api/staticHandler.js +0 -55
- package/dist/storage-content-api/staticHandler.js.map +0 -1
- package/dist/storage-content-api/types.d.ts +0 -10
- package/dist/storage-content-api/types.d.ts.map +0 -1
- package/dist/storage-content-api/types.js +0 -3
- package/dist/storage-content-api/types.js.map +0 -1
- package/dist/templates/README.md +0 -19
- package/dist/utils/build-lambda-zip.d.ts +0 -14
- package/dist/utils/build-lambda-zip.d.ts.map +0 -1
- package/dist/utils/build-lambda-zip.js +0 -81
- package/dist/utils/build-lambda-zip.js.map +0 -1
|
@@ -128,14 +128,14 @@ export const getLoginEndpoint = ({ collection, collectionOptions, endpointSlug,
|
|
|
128
128
|
grant_type: 'authorization_code',
|
|
129
129
|
redirect_uri: `${redirectDestination}${config?.routes?.api || '/api'}/${collection.slug}/${endpointSlug}/login`
|
|
130
130
|
};
|
|
131
|
-
if (strategy.collectionOptions.clientSecret) {
|
|
132
|
-
body.client_secret = strategy.collectionOptions.clientSecret;
|
|
133
|
-
}
|
|
134
131
|
debugLogger.info({
|
|
135
132
|
msg: 'Exchanging code for access token',
|
|
136
133
|
path,
|
|
137
134
|
requestBody: body
|
|
138
135
|
});
|
|
136
|
+
if (strategy.clientSecret) {
|
|
137
|
+
body.client_secret = strategy.clientSecret;
|
|
138
|
+
}
|
|
139
139
|
const tokenRes = await fetch(strategy.meta?.token_endpoint, {
|
|
140
140
|
body: new URLSearchParams(body),
|
|
141
141
|
headers: {
|
|
@@ -154,7 +154,7 @@ export const getLoginEndpoint = ({ collection, collectionOptions, endpointSlug,
|
|
|
154
154
|
tokenRes
|
|
155
155
|
});
|
|
156
156
|
// Swap for project token
|
|
157
|
-
const project_token = await getProjectToken(tokenRes.access_token,
|
|
157
|
+
const project_token = await getProjectToken(tokenRes.access_token, 'someproject');
|
|
158
158
|
const refresh_token = access_token;
|
|
159
159
|
// Store project token as access_token
|
|
160
160
|
const token = project_token.token;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/endpoints/getLoginEndpoint.ts"],"sourcesContent":["import type { CollectionConfig, Endpoint } from 'payload'\n\nimport { APIError, generateCookie, parseCookies } from 'payload'\nimport { getSafeRedirect } from 'payload/shared'\n\nimport type { Strategy } from '../strategy/index.js'\nimport type { CollectionOptions, PluginOptions, StateObj } from '../types.js'\n\nimport { getProjectToken } from '../../api/figma-api.js'\nimport { createCookieOptions } from '../utilities/createCookieOptions.js'\nimport { createDebugLogger } from '../utilities/createDebugLogger.js'\nimport { extractOrigin } from '../utilities/extractOrigin.js'\nimport { getAdminPath } from '../utilities/getAdminPath.js'\nimport { getCookieExpiration } from '../utilities/getCookieExpiration.js'\n\ninterface Args {\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n endpointSlug: string\n pluginOptions: PluginOptions\n strategy: Strategy\n}\n\nconst isAbsoluteURL = (url: string) => /^[a-z][a-z\\d+.-]*:/.test(url)\n\nexport const getLoginEndpoint = ({\n collection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n}: Args): Endpoint => ({\n handler: async (req) => {\n const { config } = req.payload\n const adminPath = getAdminPath(config)\n try {\n await strategy.ensureMeta()\n\n const path = req.pathname\n const debugLogger = createDebugLogger(req.payload, pluginOptions.debug)\n\n let jsonBody: Record<string, unknown> = {}\n\n const contentType = req.headers.get('content-type')\n\n // Type narrow PayloadRequst's Partial<Request>\n if (typeof req.json !== 'function' || typeof req.formData !== 'function') {\n debugLogger.info({\n msg: 'Request does not have json or formData methods',\n path,\n })\n\n return Response.redirect(`${pluginOptions.redirectServerURL || config.serverURL}/login`)\n }\n\n if (collectionOptions.authorizationURLParams?.response_mode === 'query') {\n if (Object.keys(req.query).length > 0) {\n jsonBody = req.query\n }\n } else if (contentType === 'application/json') {\n jsonBody = await req.json()\n } else if (contentType === 'application/x-www-form-urlencoded') {\n const formData = await req.formData()\n jsonBody = Object.fromEntries(formData.entries())\n }\n\n const stateRaw = jsonBody.state as string\n const state: StateObj = JSON.parse(Buffer.from(stateRaw, 'base64').toString('utf-8'))\n\n const redirectDestination =\n state.serverURL || pluginOptions.redirectServerURL || config.serverURL\n let failedRedirect = `${redirectDestination}${adminPath}/login`\n let redirectToUse = `${redirectDestination}${adminPath}`\n\n if (state.redirect) {\n redirectToUse = state.redirect\n }\n\n if (state.failedRedirect) {\n failedRedirect = state.failedRedirect\n }\n\n failedRedirect = getSafeRedirect({ allowAbsoluteUrls: true, redirectTo: failedRedirect })\n redirectToUse = getSafeRedirect({ allowAbsoluteUrls: true, redirectTo: redirectToUse })\n\n if (!isAbsoluteURL(failedRedirect)) {\n return Response.json({ error: 'Invalid failed redirect provided' }, { status: 403 })\n }\n if (!isAbsoluteURL(redirectToUse)) {\n return Response.json({ error: 'Invalid redirect provided' }, { status: 403 })\n }\n\n if (Array.isArray(req.payload.config.csrf) && req.payload.config.csrf.length > 0) {\n const failedRedirectOrigin = extractOrigin(failedRedirect)\n const redirectToUseOrigin = extractOrigin(redirectToUse)\n\n if (failedRedirectOrigin && !req.payload.config.csrf.includes(failedRedirectOrigin)) {\n req.payload.logger.error(\n `Failed redirect origin ${failedRedirectOrigin} is not allowed by CSRF configuration.`,\n )\n return Response.json(\n { error: 'Failed redirect origin is not allowed by CSRF configuration.' },\n { status: 403 },\n )\n }\n\n if (redirectToUseOrigin && !req.payload.config.csrf.includes(redirectToUseOrigin)) {\n req.payload.logger.error(\n `Redirect origin ${redirectToUseOrigin} is not allowed by CSRF configuration.`,\n )\n return Response.json(\n { error: 'Redirect origin is not allowed by CSRF configuration.' },\n { status: 403 },\n )\n }\n }\n\n // Verify signature\n if (strategy.name !== req.payload.decrypt(state.sig)) {\n req.payload.logger.error('Signature mismatch. Failing login and redirecting.')\n return Response.redirect(failedRedirect)\n }\n\n if (!strategy.meta?.token_endpoint) {\n debugLogger.error({\n msg: `No metadata was obtained from the identity provider. Failing login and redirecting.`,\n path,\n })\n return Response.redirect(failedRedirect)\n }\n\n debugLogger.info({ body: jsonBody, msg: 'Received login response body', path })\n\n if (!jsonBody?.code) {\n debugLogger.error({\n msg: `No authorization code present in body. Failing login and redirecting.`,\n path,\n })\n return Response.redirect(failedRedirect)\n }\n\n // Exchange `code` from body for refresh token\n const { code } = jsonBody\n\n if (typeof code !== 'string') {\n debugLogger.error({\n msg: `Authorization code present in body is not a string. Failing login and redirecting.`,\n path,\n })\n return Response.redirect(failedRedirect)\n }\n\n const body: Record<string, string> = {\n client_id: strategy.clientID,\n code,\n code_verifier: req.payload.decrypt(state.verifier),\n grant_type: 'authorization_code',\n redirect_uri: `${redirectDestination}${config?.routes?.api || '/api'}/${\n collection.slug\n }/${endpointSlug}/login`,\n }\n\n if (strategy.collectionOptions.clientSecret) {\n body.client_secret = strategy.collectionOptions.clientSecret\n }\n\n debugLogger.info({\n msg: 'Exchanging code for access token',\n path,\n requestBody: body,\n })\n\n const tokenRes = await fetch(strategy.meta?.token_endpoint, {\n body: new URLSearchParams(body),\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n method: 'POST',\n }).then((r) => r.json())\n\n debugLogger.info({ msg: 'Token Response', path, tokenRes })\n\n const { access_token, error, error_description, expires_in: refreshTokenExpires } = tokenRes\n\n debugLogger.info({ msg: 'tokenResss', tokenRes })\n\n // Swap for project token\n const project_token = await getProjectToken(\n tokenRes.access_token,\n config.custom.figma.contentSystemId,\n )\n const refresh_token = access_token\n\n // Store project token as access_token\n\n const token = project_token.token\n const expiresIn = project_token.expiresAt\n\n if (!token) {\n const errMsg = `No ${\n collectionOptions.token || 'access_token'\n } was returned from the identity provider.`\n req.payload.logger.error({ msg: errMsg, path })\n throw new APIError(errMsg)\n }\n\n const cookieOptions = createCookieOptions({ collection, headers: req.headers, pluginOptions })\n\n if (error) {\n req.payload.logger.error('Error swapping access code with access token:')\n req.payload.logger.error({ err: error, error_description })\n return Response.redirect(failedRedirect)\n }\n\n // get the payloadRedirect cookie value\n const cookies = parseCookies(req.headers)\n\n const payloadRedirect =\n 'payloadRedirect' in cookies ? (cookies.payloadRedirect as string) : ''\n\n if (!req.responseHeaders) {\n req.responseHeaders = new Headers()\n }\n\n if (payloadRedirect) {\n if (isAbsoluteURL(payloadRedirect)) {\n redirectToUse = payloadRedirect\n } else {\n redirectToUse += payloadRedirect\n }\n\n req.responseHeaders.append(\n 'Set-Cookie',\n `payloadRedirect=${redirectToUse}; Max-Age=0; Path=/;`,\n )\n }\n\n if (refresh_token && !collectionOptions.usePayloadJWT) {\n debugLogger.info('Setting refresh token cookie')\n const refreshCookie = generateCookie({\n returnCookieAsObject: false,\n ...cookieOptions,\n name: `${strategy.cookieName}-refresh`,\n value: refresh_token,\n // Default to 1 year if no expiration\n expires: getCookieExpiration(cookieOptions?.expires ?? refreshTokenExpires ?? 31_556_952),\n }) as string\n\n req.responseHeaders.append('Set-Cookie', refreshCookie)\n }\n\n const tokenExpires = cookieOptions?.expires\n ? getCookieExpiration(cookieOptions.expires)\n : new Date(expiresIn) // Project token uses epoch time\n const tokenCookie = generateCookie({\n ...cookieOptions,\n name: strategy.cookieName,\n expires: tokenExpires,\n returnCookieAsObject: false,\n value: token,\n }) as string\n\n req.responseHeaders.append('Set-Cookie', tokenCookie)\n\n return Response.redirect(redirectToUse)\n } catch (err: unknown) {\n req.payload.logger.error({ err, msg: 'Error while attempting to login', path: req.pathname })\n\n return Response.json({ error: 'Error while attempting to login' }, { status: 500 })\n }\n },\n method: collectionOptions.authorizationURLParams?.response_mode === 'query' ? 'get' : 'post',\n path: `/${endpointSlug}/login`,\n})\n"],"names":["APIError","generateCookie","parseCookies","getSafeRedirect","getProjectToken","createCookieOptions","createDebugLogger","extractOrigin","getAdminPath","getCookieExpiration","isAbsoluteURL","url","test","getLoginEndpoint","collection","collectionOptions","endpointSlug","pluginOptions","strategy","handler","req","config","payload","adminPath","ensureMeta","path","pathname","debugLogger","debug","jsonBody","contentType","headers","get","json","formData","info","msg","Response","redirect","redirectServerURL","serverURL","authorizationURLParams","response_mode","Object","keys","query","length","fromEntries","entries","stateRaw","state","JSON","parse","Buffer","from","toString","redirectDestination","failedRedirect","redirectToUse","allowAbsoluteUrls","redirectTo","error","status","Array","isArray","csrf","failedRedirectOrigin","redirectToUseOrigin","includes","logger","name","decrypt","sig","meta","token_endpoint","body","code","client_id","clientID","code_verifier","verifier","grant_type","redirect_uri","routes","api","slug","clientSecret","client_secret","requestBody","tokenRes","fetch","URLSearchParams","method","then","r","access_token","error_description","expires_in","refreshTokenExpires","project_token","custom","figma","contentSystemId","refresh_token","token","expiresIn","expiresAt","errMsg","cookieOptions","err","cookies","payloadRedirect","responseHeaders","Headers","append","usePayloadJWT","refreshCookie","returnCookieAsObject","cookieName","value","expires","tokenExpires","Date","tokenCookie"],"mappings":"AAEA,SAASA,QAAQ,EAAEC,cAAc,EAAEC,YAAY,QAAQ,UAAS;AAChE,SAASC,eAAe,QAAQ,iBAAgB;AAKhD,S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,CAAC;wBACtCC,OAAOhB;wBACP,qCAAqC;wBACrCiB,SAAS/G,oBAAoBmG,eAAeY,WAAWtB,uBAAuB;oBAChF;oBAEA9E,IAAI4F,eAAe,CAACE,MAAM,CAAC,cAAcE;gBAC3C;gBAEA,MAAMK,eAAeb,eAAeY,UAChC/G,oBAAoBmG,cAAcY,OAAO,IACzC,IAAIE,KAAKjB,WAAW,gCAAgC;;gBACxD,MAAMkB,cAAc1H,eAAe;oBACjC,GAAG2G,aAAa;oBAChBtC,MAAMpD,SAASoG,UAAU;oBACzBE,SAASC;oBACTJ,sBAAsB;oBACtBE,OAAOf;gBACT;gBAEApF,IAAI4F,eAAe,CAACE,MAAM,CAAC,cAAcS;gBAEzC,OAAOtF,SAASC,QAAQ,CAACoB;YAC3B,EAAE,OAAOmD,KAAc;gBACrBzF,IAAIE,OAAO,CAAC+C,MAAM,CAACR,KAAK,CAAC;oBAAEgD;oBAAKzE,KAAK;oBAAmCX,MAAML,IAAIM,QAAQ;gBAAC;gBAE3F,OAAOW,SAASJ,IAAI,CAAC;oBAAE4B,OAAO;gBAAkC,GAAG;oBAAEC,QAAQ;gBAAI;YACnF;QACF;QACA8B,QAAQ7E,kBAAkB0B,sBAAsB,EAAEC,kBAAkB,UAAU,QAAQ;QACtFjB,MAAM,CAAC,CAAC,EAAET,aAAa,MAAM,CAAC;IAChC,CAAA,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/endpoints/getLoginEndpoint.ts"],"sourcesContent":["import type { CollectionConfig, Endpoint } from 'payload'\n\nimport jwt from 'jsonwebtoken'\nimport { APIError, generateCookie, parseCookies } from 'payload'\nimport { getSafeRedirect } from 'payload/shared'\n\nimport type { Strategy } from '../strategy/index.js'\nimport type {\n AfterOAuthLoginHookResult,\n CollectionOptions,\n PluginOptions,\n StateObj,\n} from '../types.js'\n\nimport { getProjectToken } from '../../api/figma-api.js'\nimport { JWTValidationError, validateProjectToken } from '../../auth/jwt-validator.js'\nimport { ProjectTokenError } from '../../auth/project-token.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createCookieOptions } from '../utilities/createCookieOptions.js'\nimport { createDebugLogger } from '../utilities/createDebugLogger.js'\nimport { extractOrigin } from '../utilities/extractOrigin.js'\nimport { getAdminPath } from '../utilities/getAdminPath.js'\nimport { getCookieExpiration } from '../utilities/getCookieExpiration.js'\nimport { getSecondsFromTokenExp } from '../utilities/getSecondsFromTokenExp.js'\nimport { getTokenExp } from '../utilities/getTokenExp.js'\n\ninterface Args {\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n endpointSlug: string\n pluginOptions: PluginOptions\n strategy: Strategy\n}\n\nconst isAbsoluteURL = (url: string) => /^[a-z][a-z\\d+.-]*:/.test(url)\n\nexport const getLoginEndpoint = ({\n collection,\n collectionOptions,\n endpointSlug,\n pluginOptions,\n strategy,\n}: Args): Endpoint => ({\n handler: async (req) => {\n const { config } = req.payload\n const adminPath = getAdminPath(config)\n try {\n await strategy.ensureMeta()\n\n const path = req.pathname\n const debugLogger = createDebugLogger(req.payload, pluginOptions.debug)\n\n let jsonBody: Record<string, unknown> = {}\n\n const contentType = req.headers.get('content-type')\n\n // Type narrow PayloadRequst's Partial<Request>\n if (typeof req.json !== 'function' || typeof req.formData !== 'function') {\n debugLogger.info({\n msg: 'Request does not have json or formData methods',\n path,\n })\n\n return Response.redirect(`${pluginOptions.redirectServerURL || config.serverURL}/login`)\n }\n\n if (collectionOptions.authorizationURLParams?.response_mode === 'query') {\n if (Object.keys(req.query).length > 0) {\n jsonBody = req.query\n }\n } else if (contentType === 'application/json') {\n jsonBody = await req.json()\n } else if (contentType === 'application/x-www-form-urlencoded') {\n const formData = await req.formData()\n jsonBody = Object.fromEntries(formData.entries())\n }\n\n const stateRaw = jsonBody.state as string\n const state: StateObj = JSON.parse(Buffer.from(stateRaw, 'base64').toString('utf-8'))\n\n const redirectDestination =\n state.serverURL || pluginOptions.redirectServerURL || config.serverURL\n let failedRedirect = `${redirectDestination}${adminPath}/login`\n let redirectToUse = `${redirectDestination}${adminPath}`\n\n if (state.redirect) {\n redirectToUse = state.redirect\n }\n\n if (state.failedRedirect) {\n failedRedirect = state.failedRedirect\n }\n\n failedRedirect = getSafeRedirect({ allowAbsoluteUrls: true, redirectTo: failedRedirect })\n redirectToUse = getSafeRedirect({ allowAbsoluteUrls: true, redirectTo: redirectToUse })\n\n if (!isAbsoluteURL(failedRedirect)) {\n return Response.json({ error: 'Invalid failed redirect provided' }, { status: 403 })\n }\n if (!isAbsoluteURL(redirectToUse)) {\n return Response.json({ error: 'Invalid redirect provided' }, { status: 403 })\n }\n\n if (Array.isArray(req.payload.config.csrf) && req.payload.config.csrf.length > 0) {\n const failedRedirectOrigin = extractOrigin(failedRedirect)\n const redirectToUseOrigin = extractOrigin(redirectToUse)\n\n if (failedRedirectOrigin && !req.payload.config.csrf.includes(failedRedirectOrigin)) {\n req.payload.logger.error(\n `Failed redirect origin ${failedRedirectOrigin} is not allowed by CSRF configuration.`,\n )\n return Response.json(\n { error: 'Failed redirect origin is not allowed by CSRF configuration.' },\n { status: 403 },\n )\n }\n\n if (redirectToUseOrigin && !req.payload.config.csrf.includes(redirectToUseOrigin)) {\n req.payload.logger.error(\n `Redirect origin ${redirectToUseOrigin} is not allowed by CSRF configuration.`,\n )\n return Response.json(\n { error: 'Redirect origin is not allowed by CSRF configuration.' },\n { status: 403 },\n )\n }\n }\n\n // Verify signature\n if (strategy.name !== req.payload.decrypt(state.sig)) {\n req.payload.logger.error('Signature mismatch. Failing login and redirecting.')\n return Response.redirect(failedRedirect)\n }\n\n if (!strategy.meta?.token_endpoint) {\n debugLogger.error({\n msg: `No metadata was obtained from the identity provider. Failing login and redirecting.`,\n path,\n })\n return Response.redirect(failedRedirect)\n }\n\n debugLogger.info({ body: jsonBody, msg: 'Received login response body', path })\n\n if (!jsonBody?.code) {\n debugLogger.error({\n msg: `No authorization code present in body. Failing login and redirecting.`,\n path,\n })\n return Response.redirect(failedRedirect)\n }\n\n // Exchange `code` from body for refresh token\n const { code } = jsonBody\n\n if (typeof code !== 'string') {\n debugLogger.error({\n msg: `Authorization code present in body is not a string. Failing login and redirecting.`,\n path,\n })\n return Response.redirect(failedRedirect)\n }\n\n const body: Record<string, string> = {\n client_id: strategy.clientID,\n code,\n code_verifier: req.payload.decrypt(state.verifier),\n grant_type: 'authorization_code',\n redirect_uri: `${redirectDestination}${config?.routes?.api || '/api'}/${\n collection.slug\n }/${endpointSlug}/login`,\n }\n\n debugLogger.info({\n msg: 'Exchanging code for access token',\n path,\n requestBody: body,\n })\n\n if (strategy.clientSecret) {\n body.client_secret = strategy.clientSecret\n }\n\n const tokenRes = await fetch(strategy.meta?.token_endpoint, {\n body: new URLSearchParams(body),\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n method: 'POST',\n }).then((r) => r.json())\n\n debugLogger.info({ msg: 'Token Response', path, tokenRes })\n\n const { access_token, error, error_description, expires_in: refreshTokenExpires } = tokenRes\n\n debugLogger.info({ msg: 'tokenResss', tokenRes })\n\n // Swap for project token\n const project_token = await getProjectToken(tokenRes.access_token, 'someproject')\n const refresh_token = access_token\n\n // Store project token as access_token\n\n const token = project_token.token\n const expiresIn = project_token.expiresAt\n\n if (!token) {\n const errMsg = `No ${\n collectionOptions.token || 'access_token'\n } was returned from the identity provider.`\n req.payload.logger.error({ msg: errMsg, path })\n throw new APIError(errMsg)\n }\n\n const cookieOptions = createCookieOptions({ collection, headers: req.headers, pluginOptions })\n\n if (error) {\n req.payload.logger.error('Error swapping access code with access token:')\n req.payload.logger.error({ err: error, error_description })\n return Response.redirect(failedRedirect)\n }\n\n // get the payloadRedirect cookie value\n const cookies = parseCookies(req.headers)\n\n const payloadRedirect =\n 'payloadRedirect' in cookies ? (cookies.payloadRedirect as string) : ''\n\n if (!req.responseHeaders) {\n req.responseHeaders = new Headers()\n }\n\n if (payloadRedirect) {\n if (isAbsoluteURL(payloadRedirect)) {\n redirectToUse = payloadRedirect\n } else {\n redirectToUse += payloadRedirect\n }\n\n req.responseHeaders.append(\n 'Set-Cookie',\n `payloadRedirect=${redirectToUse}; Max-Age=0; Path=/;`,\n )\n }\n\n if (refresh_token && !collectionOptions.usePayloadJWT) {\n debugLogger.info('Setting refresh token cookie')\n const refreshCookie = generateCookie({\n returnCookieAsObject: false,\n ...cookieOptions,\n name: `${strategy.cookieName}-refresh`,\n value: refresh_token,\n // Default to 1 year if no expiration\n expires: getCookieExpiration(cookieOptions?.expires ?? refreshTokenExpires ?? 31_556_952),\n }) as string\n\n req.responseHeaders.append('Set-Cookie', refreshCookie)\n }\n\n const tokenExpires = cookieOptions?.expires\n ? getCookieExpiration(cookieOptions.expires)\n : new Date(expiresIn) // Project token uses epoch time\n const tokenCookie = generateCookie({\n ...cookieOptions,\n name: strategy.cookieName,\n expires: tokenExpires,\n returnCookieAsObject: false,\n value: token,\n }) as string\n\n req.responseHeaders.append('Set-Cookie', tokenCookie)\n\n return Response.redirect(redirectToUse)\n } catch (err: unknown) {\n req.payload.logger.error({ err, msg: 'Error while attempting to login', path: req.pathname })\n\n return Response.json({ error: 'Error while attempting to login' }, { status: 500 })\n }\n },\n method: collectionOptions.authorizationURLParams?.response_mode === 'query' ? 'get' : 'post',\n path: `/${endpointSlug}/login`,\n})\n"],"names":["APIError","generateCookie","parseCookies","getSafeRedirect","getProjectToken","createCookieOptions","createDebugLogger","extractOrigin","getAdminPath","getCookieExpiration","isAbsoluteURL","url","test","getLoginEndpoint","collection","collectionOptions","endpointSlug","pluginOptions","strategy","handler","req","config","payload","adminPath","ensureMeta","path","pathname","debugLogger","debug","jsonBody","contentType","headers","get","json","formData","info","msg","Response","redirect","redirectServerURL","serverURL","authorizationURLParams","response_mode","Object","keys","query","length","fromEntries","entries","stateRaw","state","JSON","parse","Buffer","from","toString","redirectDestination","failedRedirect","redirectToUse","allowAbsoluteUrls","redirectTo","error","status","Array","isArray","csrf","failedRedirectOrigin","redirectToUseOrigin","includes","logger","name","decrypt","sig","meta","token_endpoint","body","code","client_id","clientID","code_verifier","verifier","grant_type","redirect_uri","routes","api","slug","requestBody","clientSecret","client_secret","tokenRes","fetch","URLSearchParams","method","then","r","access_token","error_description","expires_in","refreshTokenExpires","project_token","refresh_token","token","expiresIn","expiresAt","errMsg","cookieOptions","err","cookies","payloadRedirect","responseHeaders","Headers","append","usePayloadJWT","refreshCookie","returnCookieAsObject","cookieName","value","expires","tokenExpires","Date","tokenCookie"],"mappings":"AAGA,SAASA,QAAQ,EAAEC,cAAc,EAAEC,YAAY,QAAQ,UAAS;AAChE,SAASC,eAAe,QAAQ,iBAAgB;AAUhD,SAASC,eAAe,QAAQ,yBAAwB;AAIxD,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,aAAa,QAAQ,gCAA+B;AAC7D,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,mBAAmB,QAAQ,sCAAqC;AAYzE,MAAMC,gBAAgB,CAACC,MAAgB,qBAAqBC,IAAI,CAACD;AAEjE,OAAO,MAAME,mBAAmB,CAAC,EAC/BC,UAAU,EACVC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,QAAQ,EACH,GAAgB,CAAA;QACrBC,SAAS,OAAOC;YACd,MAAM,EAAEC,MAAM,EAAE,GAAGD,IAAIE,OAAO;YAC9B,MAAMC,YAAYf,aAAaa;YAC/B,IAAI;gBACF,MAAMH,SAASM,UAAU;gBAEzB,MAAMC,OAAOL,IAAIM,QAAQ;gBACzB,MAAMC,cAAcrB,kBAAkBc,IAAIE,OAAO,EAAEL,cAAcW,KAAK;gBAEtE,IAAIC,WAAoC,CAAC;gBAEzC,MAAMC,cAAcV,IAAIW,OAAO,CAACC,GAAG,CAAC;gBAEpC,+CAA+C;gBAC/C,IAAI,OAAOZ,IAAIa,IAAI,KAAK,cAAc,OAAOb,IAAIc,QAAQ,KAAK,YAAY;oBACxEP,YAAYQ,IAAI,CAAC;wBACfC,KAAK;wBACLX;oBACF;oBAEA,OAAOY,S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[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAkC,MAAM,EAAE,MAAM,SAAS,CAAA;AAErE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAc/C,eAAO,MAAM,YAAY,kBACP,aAAa,KAAG,MAoO/B,CAAA"}
|
package/dist/oauth/index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { fieldAffectsData } from 'payload/shared';
|
|
2
1
|
import { defaultVerify } from './defaults.js';
|
|
3
2
|
import { getLoginEndpoint } from './endpoints/getLoginEndpoint.js';
|
|
4
3
|
import { getLogoutEndpoint } from './endpoints/getLogoutEndpoint.js';
|
|
@@ -47,7 +46,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
47
46
|
disabled,
|
|
48
47
|
endpointSlug
|
|
49
48
|
},
|
|
50
|
-
path: '@payloadcms/
|
|
49
|
+
path: '@payloadcms/plugin-oauth2/client#DefaultLoginButton'
|
|
51
50
|
};
|
|
52
51
|
}
|
|
53
52
|
return {
|
|
@@ -63,7 +62,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
63
62
|
disabled,
|
|
64
63
|
endpointSlug
|
|
65
64
|
},
|
|
66
|
-
path: '@payloadcms/
|
|
65
|
+
path: '@payloadcms/plugin-oauth2/client#LogoutButton'
|
|
67
66
|
}
|
|
68
67
|
}
|
|
69
68
|
} : {},
|
|
@@ -85,45 +84,14 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
85
84
|
if (collectionOptions.usePayloadJWT) {
|
|
86
85
|
cookieName = `${config.cookiePrefix || 'payload'}-token`;
|
|
87
86
|
}
|
|
88
|
-
// Check if email field exists, if not add it
|
|
89
|
-
const hasEmailField = existingCollection.fields.some((field)=>'name' in field && field.name === 'email');
|
|
90
|
-
// Add email field to collection before getting username field
|
|
91
|
-
// This ensures getUsernameField can find the email field if it's configured as the username
|
|
92
|
-
const collectionWithEmail = hasEmailField ? existingCollection : {
|
|
93
|
-
...existingCollection,
|
|
94
|
-
fields: [
|
|
95
|
-
...existingCollection.fields,
|
|
96
|
-
{
|
|
97
|
-
name: 'email',
|
|
98
|
-
type: 'email',
|
|
99
|
-
admin: {
|
|
100
|
-
description: 'Managed by Figma',
|
|
101
|
-
readOnly: true
|
|
102
|
-
},
|
|
103
|
-
unique: true
|
|
104
|
-
}
|
|
105
|
-
]
|
|
106
|
-
};
|
|
107
87
|
const usernameField = getUsernameField({
|
|
108
|
-
collection:
|
|
88
|
+
collection: existingCollection,
|
|
109
89
|
collectionOptions
|
|
110
90
|
});
|
|
111
|
-
// Make username field readOnly (and add description for email fields)
|
|
112
|
-
const readOnlyUsernameField = {
|
|
113
|
-
...usernameField,
|
|
114
|
-
admin: {
|
|
115
|
-
...usernameField.admin || {},
|
|
116
|
-
...usernameField.name === 'email' ? {
|
|
117
|
-
description: 'Managed by Figma'
|
|
118
|
-
} : {},
|
|
119
|
-
readOnly: true
|
|
120
|
-
}
|
|
121
|
-
};
|
|
122
|
-
const isUsernameFieldString = typeof adminCollectionOptions.usernameField === 'string';
|
|
123
91
|
const fields = [
|
|
124
|
-
...
|
|
125
|
-
...
|
|
126
|
-
|
|
92
|
+
...existingCollection.fields,
|
|
93
|
+
...typeof adminCollectionOptions.usernameField === 'string' ? [] : [
|
|
94
|
+
usernameField
|
|
127
95
|
]
|
|
128
96
|
];
|
|
129
97
|
if (disabled) {
|
|
@@ -134,6 +102,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
134
102
|
}
|
|
135
103
|
const strategy = new Strategy({
|
|
136
104
|
clientID: collectionOptions.clientID,
|
|
105
|
+
clientSecret: collectionOptions.clientSecret,
|
|
137
106
|
collection: existingCollection,
|
|
138
107
|
collectionOptions,
|
|
139
108
|
cookieName,
|
|
@@ -165,10 +134,6 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
165
134
|
}
|
|
166
135
|
return {
|
|
167
136
|
...existingCollection,
|
|
168
|
-
access: {
|
|
169
|
-
...existingCollection.access || {},
|
|
170
|
-
create: ()=>false
|
|
171
|
-
},
|
|
172
137
|
auth: {
|
|
173
138
|
...typeof existingCollection.auth === 'object' ? existingCollection.auth : {},
|
|
174
139
|
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 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 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","identityMetadata","verify","authStrategy","authenticate","bind","disableLocalStrategy","undefined","access","create","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,QAAQ,kCAAiC;AAElE,OAAO,MAAMC,eACX,CAACC,gBACD,CAACC;QACC,MAAM,EAAEC,aAAaC,oBAAoB,EAAEC,KAAK,EAAEC,QAAQ,EAAE,GAAGL;QAE/D,MAAMM,eAAeN,eAAeM,gBAAgB;QACpD,8FAA8F;QAC9F,MAAMC,eAAeP,eAAeM,gBAAgB;QAEpD,MAAME,sBAAsBX,uBAAuBI;QACnD,MAAMQ,yBAAyBN,qBAAqBO,IAAI,CACtD,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASH;QAGzB,IAAI,CAACC,wBAAwB;YAC3B,MAAM,IAAIG,MACR,CAAC,uDAAuD,EAAEJ,oBAAoB,CAAC,CAAC;QAEpF;QAEA,IAAIK,cAAc;QAElB,IAAIJ,uBAAuBI,WAAW,KAAK,OAAO;YAChDA,cAAc;QAChB,OAAO,IAAI,OAAOJ,uBAAuBI,WAAW,KAAK,UAAU;YACjEA,cAAc;gBACZC,aAAa;oBACXT;oBACAE;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AtD,kBAAkB;4BAChBmD,YAAYhB;4BACZlB;4BACAP;4BACA4C;wBACF;wBACApD,2BAA2B;4BACzBiD,YAAYhB;4BACZC;4BACAnB;4BACAP;4BACA4C;wBACF;qBACD;oBACDb;oBACA2B,OAAO;wBACL,GAAIjC,mBAAmBiC,KAAK,IAAI,CAAC,CAAC;wBAClCC,aAAa;+BACP,OAAOlC,mBAAmBiC,KAAK,KAAK,YACxCpC,MAAMC,OAAO,CAACE,mBAAmBiC,KAAK,CAACC,WAAW,IAC9ClC,mBAAmBiC,KAAK,CAACC,WAAW,GACpC,EAAE;4BACNlE,eAAe;gCACbgD,YAAYhB;gCACZE;gCACA3B;4BACF;yBACD;wBACD4D,IAAI;+BACE,OAAOnC,mBAAmBiC,KAAK,KAAK,YACxCpC,MAAMC,OAAO,CAACE,mBAAmBiC,KAAK,CAACE,EAAE,IACrCnC,mBAAmBiC,KAAK,CAACE,EAAE,GAC3B,EAAE;4BACN,mEAAmE;+BAC/D,CAAClC,kBAAkBE,aAAa,GAAG;gCAAClC,UAAU;oCAAEiC;gCAAW;6BAAG,GAAG,EAAE;yBACxE;wBACDkC,SAAS;+BACH,OAAOpC,mBAAmBiC,KAAK,KAAK,YACxCpC,MAAMC,OAAO,CAACE,mBAAmBiC,KAAK,CAACG,OAAO,IAC1CpC,mBAAmBiC,KAAK,CAACG,OAAO,GAChC,EAAE;4BACNlE,eAAe;gCAAEK;gCAAe4C;4BAAS;yBAC1C;oBACH;gBACF;YACF;QACF;IACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/oauth/index.ts"],"sourcesContent":["import type { AuthStrategy, IncomingAuthType, Plugin } from 'payload'\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/plugin-oauth2/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/plugin-oauth2/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 const usernameField = getUsernameField({\n collection: existingCollection,\n collectionOptions,\n })\n\n const fields = [\n ...existingCollection.fields,\n ...(typeof adminCollectionOptions.usernameField === 'string' ? [] : [usernameField]),\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":["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","usernameField","collection","fields","strategy","clientID","clientSecret","identityMetadata","verify","authStrategy","name","authenticate","bind","disableLocalStrategy","undefined","auth","strategies","endpoints","hooks","afterLogout","me","refresh"],"mappings":"AAIA,SAASA,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,QAAQ,kCAAiC;AAElE,OAAO,MAAMC,eACX,CAACC,gBACD,CAACC;QACC,MAAM,EAAEC,aAAaC,oBAAoB,EAAEC,KAAK,EAAEC,QAAQ,EAAE,GAAGL;QAE/D,MAAMM,eAAeN,eAAeM,gBAAgB;QACpD,8FAA8F;QAC9F,MAAMC,eAAeP,eAAeM,gBAAgB;QAEpD,MAAME,sBAAsBX,uBAAuBI;QACnD,MAAMQ,yBAAyBN,qBAAqBO,IAAI,CACtD,CAAC,EAAEC,IAAI,EAAE,GAAKA,SAASH;QAGzB,IAAI,CAACC,wBAAwB;YAC3B,MAAM,IAAIG,MACR,CAAC,uDAAuD,EAAEJ,oBAAoB,CAAC,CAAC;QAEpF;QAEA,IAAIK,cAAc;QAElB,IAAIJ,uBAAuBI,WAAW,KAAK,OAAO;YAChDA,cAAc;QAChB,OAAO,IAAI,OAAOJ,uBAAuBI,WAAW,KAAK,UAAU;YACjEA,cAAc;gBACZC,aAAa;oBACXT;oBACAE;gBACF;gBACAQ,MAAMN,uBAAuBI,WAAW;YAC1C;QACF,OAAO,IAAI,OAAOJ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K;gCAAeiC;4BAAS;yBAC1C;oBACH;gBACF;YACF;QACF;IACF,EAAC"}
|
|
@@ -4,6 +4,7 @@ import * as jose from 'jose';
|
|
|
4
4
|
import type { CollectionOptions, PluginOptions, VerifyFunction } from '../types.js';
|
|
5
5
|
export interface Options {
|
|
6
6
|
clientID: string;
|
|
7
|
+
clientSecret?: string;
|
|
7
8
|
collection: CollectionConfig;
|
|
8
9
|
collectionOptions: CollectionOptions;
|
|
9
10
|
cookieName: string;
|
|
@@ -15,6 +16,7 @@ export interface Options {
|
|
|
15
16
|
}
|
|
16
17
|
export declare class Strategy {
|
|
17
18
|
clientID: string;
|
|
19
|
+
clientSecret?: string;
|
|
18
20
|
collection: CollectionConfig;
|
|
19
21
|
collectionOptions: CollectionOptions;
|
|
20
22
|
cookieName: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/oauth/strategy/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAEnC,OAAO,KAAK,EACV,wBAAwB,EACxB,kBAAkB,EAClB,gBAAgB,EAChB,OAAO,EACR,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAG5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/oauth/strategy/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAEnC,OAAO,KAAK,EACV,wBAAwB,EACxB,kBAAkB,EAClB,gBAAgB,EAChB,OAAO,EACR,MAAM,SAAS,CAAA;AAEhB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAG5B,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAUnF,MAAM,WA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ACb,OAAO,EACP,OAAO,GACR,EAAE,wBAAwB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAyJnD,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAe3B,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC;IAkD1B,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IA6C1D,SAAS,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,aAAa,GAAG,OAAO,CAAC,KAAK,GAAG,GAAG,CAAC,UAAU,GAAG,IAAI,CAAC;CAmB3F;AAED,KAAK,aAAa,GAAG;IACnB,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;CACd,CAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as jose from 'jose';
|
|
2
2
|
import { APIError, parseCookies } from 'payload';
|
|
3
|
-
import {
|
|
3
|
+
import { 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';
|
|
@@ -8,6 +8,7 @@ import { mergeHeaders } from '../utilities/mergeHeaders.js';
|
|
|
8
8
|
import { refreshTokens } from '../utilities/refreshTokens.js';
|
|
9
9
|
export class Strategy {
|
|
10
10
|
clientID;
|
|
11
|
+
clientSecret;
|
|
11
12
|
collection;
|
|
12
13
|
collectionOptions;
|
|
13
14
|
cookieName;
|
|
@@ -27,6 +28,7 @@ export class Strategy {
|
|
|
27
28
|
this.verify = options.verify;
|
|
28
29
|
this.cookieName = options.cookieName;
|
|
29
30
|
this.clientID = options.clientID;
|
|
31
|
+
this.clientSecret = options.clientSecret;
|
|
30
32
|
this.identityMetadataURL = options.identityMetadata;
|
|
31
33
|
this.name = options.strategyName;
|
|
32
34
|
this.collection = options.collection;
|
|
@@ -61,11 +63,7 @@ export class Strategy {
|
|
|
61
63
|
}
|
|
62
64
|
}
|
|
63
65
|
if (!oauthToken) {
|
|
64
|
-
|
|
65
|
-
// This allows authentication to succeed for the current request even when
|
|
66
|
-
// cookies cannot be updated. The cookie will be refreshed on the next
|
|
67
|
-
// full page load when canSetHeaders=true.
|
|
68
|
-
if (refreshToken) {
|
|
66
|
+
if (refreshToken && canSetHeaders) {
|
|
69
67
|
debugLogger.info({
|
|
70
68
|
msg: 'No access token found, but refresh token exists. Attempting to refresh...',
|
|
71
69
|
refreshToken
|
|
@@ -85,20 +83,11 @@ export class Strategy {
|
|
|
85
83
|
msg: 'Token refreshed. Verifying...',
|
|
86
84
|
verifyResult
|
|
87
85
|
});
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
// has already started and cookies cannot be modified.
|
|
91
|
-
if (canSetHeaders) {
|
|
92
|
-
if (verifyResult.responseHeaders) {
|
|
93
|
-
mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
|
|
94
|
-
}
|
|
95
|
-
return {
|
|
96
|
-
responseHeaders: refreshed.headers,
|
|
97
|
-
user: verifyResult.user
|
|
98
|
-
};
|
|
86
|
+
if (verifyResult.responseHeaders) {
|
|
87
|
+
mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
|
|
99
88
|
}
|
|
100
|
-
// Authenticate this request without updating cookies
|
|
101
89
|
return {
|
|
90
|
+
responseHeaders: refreshed.headers,
|
|
102
91
|
user: verifyResult.user
|
|
103
92
|
};
|
|
104
93
|
} else {
|
|
@@ -108,10 +97,11 @@ export class Strategy {
|
|
|
108
97
|
refreshToken
|
|
109
98
|
});
|
|
110
99
|
}
|
|
100
|
+
} else {
|
|
101
|
+
return {
|
|
102
|
+
user: null
|
|
103
|
+
};
|
|
111
104
|
}
|
|
112
|
-
return {
|
|
113
|
-
user: null
|
|
114
|
-
};
|
|
115
105
|
}
|
|
116
106
|
let oauthTokenVerifyResult = null;
|
|
117
107
|
// First, try to verify token
|
|
@@ -146,10 +136,7 @@ export class Strategy {
|
|
|
146
136
|
});
|
|
147
137
|
}
|
|
148
138
|
}
|
|
149
|
-
|
|
150
|
-
// Same pattern as above: refresh regardless of canSetHeaders to support RSC navigation,
|
|
151
|
-
// but only update cookies when canSetHeaders=true.
|
|
152
|
-
if (oauthTokenVerifyResult instanceof JWTValidationError && oauthTokenVerifyResult.code === 'EXPIRED' && refreshToken && !this.collectionOptions.usePayloadJWT) {
|
|
139
|
+
if (oauthTokenVerifyResult instanceof Error && oauthTokenVerifyResult.name === 'TokenExpiredError' && refreshToken && !this.collectionOptions.usePayloadJWT && canSetHeaders) {
|
|
153
140
|
const refreshed = await refreshTokens({
|
|
154
141
|
payload,
|
|
155
142
|
refreshToken,
|
|
@@ -170,17 +157,11 @@ export class Strategy {
|
|
|
170
157
|
msg: 'Token refreshed. Verifying...',
|
|
171
158
|
verifyResult
|
|
172
159
|
});
|
|
173
|
-
if (
|
|
174
|
-
|
|
175
|
-
mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
|
|
176
|
-
}
|
|
177
|
-
return {
|
|
178
|
-
responseHeaders: refreshed.headers,
|
|
179
|
-
user: verifyResult.user
|
|
180
|
-
};
|
|
160
|
+
if (verifyResult.responseHeaders) {
|
|
161
|
+
mergeHeaders(verifyResult.responseHeaders, refreshed.headers);
|
|
181
162
|
}
|
|
182
|
-
// Authenticate this request without updating cookies
|
|
183
163
|
return {
|
|
164
|
+
responseHeaders: refreshed.headers,
|
|
184
165
|
user: verifyResult.user
|
|
185
166
|
};
|
|
186
167
|
} else {
|
|
@@ -219,10 +200,6 @@ export class Strategy {
|
|
|
219
200
|
for(let attempt = 1; attempt <= 5; attempt++){
|
|
220
201
|
try {
|
|
221
202
|
this.meta = await fetch(this.identityMetadataURL).then((res)=>res.json());
|
|
222
|
-
if (this.meta) {
|
|
223
|
-
// TODO: This is a hack to get the DefaultLoginButton to work with dynamic OAuth client registration
|
|
224
|
-
this.meta.authorization_endpoint = this.meta?.authorization_endpoint + '/cms';
|
|
225
|
-
}
|
|
226
203
|
this.debugLog(`fetchMeta - success on attempt ${attempt}`);
|
|
227
204
|
if (this.meta?.jwks_uri) {
|
|
228
205
|
this.jwks = await fetch(this.meta.jwks_uri).then((res)=>res.json());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/strategy/index.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\n/* eslint-disable @typescript-eslint/restrict-template-expressions */\nimport type {\n AuthStrategyFunctionArgs,\n AuthStrategyResult,\n CollectionConfig,\n Payload,\n} from 'payload'\n\nimport * as jose from 'jose'\nimport { APIError, parseCookies } from 'payload'\n\nimport type { CollectionOptions, PluginOptions, VerifyFunction } from '../types.js'\n\nimport { JWTValidationError, validateProjectToken } from '../../auth/jwt-validator.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createDebugLogger } from '../utilities/createDebugLogger.js'\nimport { getTokenExp } from '../utilities/getTokenExp.js'\nimport { mergeHeaders } from '../utilities/mergeHeaders.js'\nimport { refreshTokens } from '../utilities/refreshTokens.js'\n\nexport interface Options {\n clientID: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n debug?: boolean\n identityMetadata: string\n pluginOptions: PluginOptions\n strategyName: string\n verify: VerifyFunction\n}\n\nexport class Strategy {\n clientID: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n\n debug: boolean\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n debugLog: (...args: any[]) => void\n\n identityMetadataURL: string\n jwks?: {\n keys: jose.JWK[]\n }\n meta?: {\n authorization_endpoint: string\n end_session_endpoint: string\n jwks_uri: string\n token_endpoint: string\n userinfo_endpoint: string\n }\n metaLastFetchedTime?: Date\n\n metaPromise?: Promise<void>\n metaPromiseResolve?: () => void\n name: string\n pluginOptions: PluginOptions\n verify: VerifyFunction\n\n constructor(options: Options) {\n this.verify = options.verify\n this.cookieName = options.cookieName\n this.clientID = options.clientID\n this.identityMetadataURL = options.identityMetadata\n this.name = options.strategyName\n this.collection = options.collection\n this.collectionOptions = options.collectionOptions\n this.pluginOptions = options.pluginOptions\n this.debug = options.debug || false\n // eslint-disable-next-line no-console, @typescript-eslint/no-explicit-any\n this.debugLog = options.debug ? (...args: any[]) => console.log(...args) : () => null\n // Prevent wokiness with `this`\n this.ensureMeta = this.ensureMeta.bind(this)\n }\n\n async authenticate({\n canSetHeaders,\n headers,\n payload,\n }: AuthStrategyFunctionArgs): Promise<AuthStrategyResult> {\n const debugLogger = createDebugLogger(payload, this.debug)\n await this.ensureMeta()\n\n const cookies = parseCookies(headers)\n\n let oauthToken = cookies.get(this.cookieName)\n const refreshToken = cookies.get(`${this.cookieName}-refresh`)\n\n debugLogger.info({\n msg: 'Retrieved tokens from cookies',\n oauthToken,\n refreshToken,\n })\n\n if (!this.collectionOptions.disableJWTFromHeader) {\n // Parse Authorization header if exists\n const jwtFromHeader = headers.get('authorization')\n if (typeof jwtFromHeader === 'string' && jwtFromHeader.startsWith('Bearer ')) {\n debugLogger.info({\n jwtFromHeader,\n msg: 'Found bearer token in authorization header',\n })\n oauthToken = jwtFromHeader.replace('Bearer ', '')\n }\n }\n\n if (!oauthToken) {\n // Attempt refresh even when canSetHeaders=false (e.g., during RSC navigation).\n // This allows authentication to succeed for the current request even when\n // cookies cannot be updated. The cookie will be refreshed on the next\n // full page load when canSetHeaders=true.\n if (refreshToken) {\n debugLogger.info({\n msg: 'No access token found, but refresh token exists. Attempting to refresh...',\n refreshToken,\n })\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n // Only return response headers (to set cookies) when canSetHeaders is true.\n // During RSC navigation, canSetHeaders=false because response streaming\n // has already started and cookies cannot be modified.\n if (canSetHeaders) {\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n }\n\n // Authenticate this request without updating cookies\n return {\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n }\n\n return {\n user: null,\n }\n }\n\n let oauthTokenVerifyResult: Error | jwt.JwtPayload | null = null\n\n // First, try to verify token\n if (oauthToken) {\n oauthTokenVerifyResult = await this.jwtVerify({ payload, token: oauthToken })\n\n // If verify comes back null, there is no user\n if (oauthTokenVerifyResult === null) {\n return {\n user: null,\n }\n }\n\n // If verify comes back truthy, use it\n // but first set exp from refresh token\n // because access exp is likely very short lived\n if (\n typeof oauthTokenVerifyResult === 'object' &&\n !(oauthTokenVerifyResult instanceof Error)\n ) {\n if (refreshToken) {\n const refreshTokenExp = getTokenExp({ debugLogger, token: refreshToken })\n\n if (refreshTokenExp) {\n oauthTokenVerifyResult.exp = refreshTokenExp\n }\n }\n\n return this.verify({\n headers,\n payload,\n token: oauthTokenVerifyResult,\n })\n }\n }\n\n // Handle expired access token with valid refresh token.\n // Same pattern as above: refresh regardless of canSetHeaders to support RSC navigation,\n // but only update cookies when canSetHeaders=true.\n if (\n oauthTokenVerifyResult instanceof JWTValidationError &&\n oauthTokenVerifyResult.code === 'EXPIRED' &&\n refreshToken &&\n !this.collectionOptions.usePayloadJWT\n ) {\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n\n debugLogger.info({\n msg: 'Token expired. Refreshing...',\n refreshed,\n refreshToken,\n })\n\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n if (canSetHeaders) {\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n }\n\n // Authenticate this request without updating cookies\n return {\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n }\n\n return {\n user: null,\n }\n }\n\n async ensureMeta(): Promise<void> {\n if (this.metaPromise) {\n this.debugLog('strategy - metaPromise exists. Waiting for it to resolve...')\n await this.metaPromise\n }\n\n // If no meta or this.metaLastFetchedTime is more than 24 hours old, fetch meta\n if (!this.metaLastFetchedTime || Date.now() - this.metaLastFetchedTime.getTime() > 86_400_000) {\n this.debugLog(\n `Meta is stale. Fetching... Last fetched: ${this.metaLastFetchedTime || 'never'}`,\n )\n await this.fetchMeta()\n }\n }\n\n async fetchMeta(): Promise<void> {\n // If already in-flight, return the existing promise\n if (this.metaPromise) {\n this.debugLog('fetchMeta - returning existing metaPromise')\n return this.metaPromise\n }\n\n this.debugLog('fetchMeta - creating new metaPromise...')\n\n // Build the shared promise\n this.metaPromise = (async () => {\n let lastError: unknown\n\n for (let attempt = 1; attempt <= 5; attempt++) {\n try {\n this.meta = await fetch(this.identityMetadataURL).then((res) => res.json())\n\n if (this.meta) {\n // TODO: This is a hack to get the DefaultLoginButton to work with dynamic OAuth client registration\n this.meta.authorization_endpoint = this.meta?.authorization_endpoint + '/cms'\n }\n\n this.debugLog(`fetchMeta - success on attempt ${attempt}`)\n\n if (this.meta?.jwks_uri) {\n this.jwks = await fetch(this.meta.jwks_uri).then((res) => res.json())\n }\n\n this.metaLastFetchedTime = new Date()\n this.debugLog(`fetchMeta - finished at ${this.metaLastFetchedTime.toISOString()}`)\n return\n } catch (error: unknown) {\n lastError = error\n this.debugLog(`fetchMeta - FAILED attempt ${attempt}/5: ${(error as Error)?.message}`)\n\n if (attempt < 5) {\n // Exponential backoff (up to 1s)\n await new Promise((resolve) => setTimeout(resolve, Math.min(attempt * 200, 1000)))\n }\n }\n }\n\n throw new APIError(\n `Failed to fetch identity metadata from \"${this.identityMetadataURL}\". Last error: ${\n (lastError as Error)?.message ?? 'unknown'\n }`,\n )\n })()\n\n try {\n await this.metaPromise\n } finally {\n this.metaPromise = undefined\n }\n }\n\n async generateOidcPEM(kid: string, alg: string): Promise<string> {\n const keys = this && this.jwks && Array.isArray(this.jwks.keys) ? this.jwks.keys : null\n\n let pubKey: null | string = null\n let foundKey = false\n\n if (!kid) {\n throw new Error('kid is missing')\n }\n\n if (!alg) {\n throw new Error('alg is missing')\n }\n\n if (!keys) {\n throw new Error('keys is missing')\n }\n\n for (const key of keys) {\n if (!('kid' in key) || key.kid !== kid) {\n continue\n }\n\n const cryptoKey = await jose.importJWK(key, alg)\n if (!(cryptoKey instanceof CryptoKey)) {\n throw new Error('importJWK did not return a CryptoKey')\n }\n\n pubKey = await jose.exportSPKI(cryptoKey)\n foundKey = true\n\n break\n }\n\n if (!foundKey) {\n throw new Error('a key with the specific kid cannot be found')\n }\n\n if (!pubKey) {\n throw new Error('generating public key pem failed')\n }\n\n return pubKey\n }\n\n async jwtVerify({ payload, token }: JwtVerifyArgs): Promise<Error | jwt.JwtPayload | null> {\n try {\n const verified = await validateProjectToken(token, getEnvironment())\n if (typeof verified !== 'string') {\n return verified\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: 'Error verifying jwt token',\n })\n\n if (err instanceof Error) {\n return err\n }\n return null\n }\n return null\n }\n}\n\ntype JwtVerifyArgs = {\n payload: Payload\n token: string\n}\n"],"names":["jose","APIError","parseCookies","JWTValidationError","validateProjectToken","getEnvironment","createDebugLogger","getTokenExp","mergeHeaders","refreshTokens","Strategy","clientID","collection","collectionOptions","cookieName","debug","debugLog","identityMetadataURL","jwks","meta","metaLastFetchedTime","metaPromise","metaPromiseResolve","name","pluginOptions","verify","options","identityMetadata","strategyName","args","console","log","ensureMeta","bind","authenticate","canSetHeaders","headers","payload","debugLogger","cookies","oauthToken","get","refreshToken","info","msg","disableJWTFromHeader","jwtFromHeader","startsWith","replace","refreshed","strategy","verifyResult","token","decodedOauthToken","responseHeaders","user","oauthTokenVerifyResult","jwtVerify","Error","refreshTokenExp","exp","code","usePayloadJWT","Date","now","getTime","fetchMeta","lastError","attempt","fetch","then","res","json","authorization_endpoint","jwks_uri","toISOString","error","message","Promise","resolve","setTimeout","Math","min","undefined","generateOidcPEM","kid","alg","keys","Array","isArray","pubKey","foundKey","key","cryptoKey","importJWK","CryptoKey","exportSPKI","verified","err","logger"],"mappings":"AASA,YAAYA,UAAU,OAAM;AAC5B,SAASC,QAAQ,EAAEC,YAAY,QAAQ,UAAS;AAIhD,SAASC,kBAAkB,EAAEC,oBAAoB,QAAQ,8BAA6B;AACtF,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,aAAa,QAAQ,gCAA+B;AAc7D,OAAO,MAAMC;IACXC,SAAgB;IAChBC,WAA4B;IAC5BC,kBAAoC;IACpCC,WAAkB;IAElBC,MAAc;IAEd,8DAA8D;IAC9DC,SAAkC;IAElCC,oBAA2B;IAC3BC,KAEC;IACDC,KAMC;IACDC,oBAA0B;IAE1BC,YAA2B;IAC3BC,mBAA+B;IAC/BC,KAAY;IACZC,cAA4B;IAC5BC,OAAsB;IAEtB,YAAYC,OAAgB,CAAE;QAC5B,IAAI,CAACD,MAAM,GAAGC,QAAQD,MAAM;QAC5B,IAAI,CAACX,UAAU,GAAGY,QAAQZ,UAAU;QACpC,IAAI,CAACH,QAAQ,GAAGe,QAAQf,QAAQ;QAChC,IAAI,CAACM,mBAAmB,GAAGS,QAAQC,gBAAgB;QACnD,IAAI,CAACJ,IAAI,GAAGG,QAAQE,YAAY;QAChC,IAAI,CAAChB,UAAU,GAAGc,QAAQd,UAAU;QACpC,IAAI,CAACC,iBAAiB,GAAGa,QAAQb,iBAAiB;QAClD,IAAI,CAACW,aAAa,GAAGE,QAAQF,aAAa;QAC1C,IAAI,CAACT,KAAK,GAAGW,QAAQX,KAAK,IAAI;QAC9B,0EAA0E;QAC1E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IAAIsD,eAAexC,OAAO;gBACxB,OAAOwC;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 { ProjectTokenError } from '../../auth/project-token.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createDebugLogger } from '../utilities/createDebugLogger.js'\nimport { getTokenExp } from '../utilities/getTokenExp.js'\nimport { mergeHeaders } from '../utilities/mergeHeaders.js'\nimport { refreshTokens } from '../utilities/refreshTokens.js'\n\nexport interface Options {\n clientID: string\n clientSecret?: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n debug?: boolean\n identityMetadata: string\n pluginOptions: PluginOptions\n strategyName: string\n verify: VerifyFunction\n}\n\nexport class Strategy {\n clientID: string\n clientSecret?: string\n collection: CollectionConfig\n collectionOptions: CollectionOptions\n cookieName: string\n\n debug: boolean\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n debugLog: (...args: any[]) => void\n\n identityMetadataURL: string\n jwks?: {\n keys: jose.JWK[]\n }\n meta?: {\n authorization_endpoint: string\n end_session_endpoint: string\n jwks_uri: string\n token_endpoint: string\n userinfo_endpoint: string\n }\n metaLastFetchedTime?: Date\n\n metaPromise?: Promise<void>\n metaPromiseResolve?: () => void\n name: string\n pluginOptions: PluginOptions\n verify: VerifyFunction\n\n constructor(options: Options) {\n this.verify = options.verify\n this.cookieName = options.cookieName\n this.clientID = options.clientID\n this.clientSecret = options.clientSecret\n this.identityMetadataURL = options.identityMetadata\n this.name = options.strategyName\n this.collection = options.collection\n this.collectionOptions = options.collectionOptions\n this.pluginOptions = options.pluginOptions\n this.debug = options.debug || false\n // eslint-disable-next-line no-console, @typescript-eslint/no-explicit-any\n this.debugLog = options.debug ? (...args: any[]) => console.log(...args) : () => null\n // Prevent wokiness with `this`\n this.ensureMeta = this.ensureMeta.bind(this)\n }\n\n async authenticate({\n canSetHeaders,\n headers,\n payload,\n }: AuthStrategyFunctionArgs): Promise<AuthStrategyResult> {\n const debugLogger = createDebugLogger(payload, this.debug)\n await this.ensureMeta()\n\n const cookies = parseCookies(headers)\n\n let oauthToken = cookies.get(this.cookieName)\n const refreshToken = cookies.get(`${this.cookieName}-refresh`)\n\n debugLogger.info({\n msg: 'Retrieved tokens from cookies',\n oauthToken,\n refreshToken,\n })\n\n if (!this.collectionOptions.disableJWTFromHeader) {\n // Parse Authorization header if exists\n const jwtFromHeader = headers.get('authorization')\n if (typeof jwtFromHeader === 'string' && jwtFromHeader.startsWith('Bearer ')) {\n debugLogger.info({\n jwtFromHeader,\n msg: 'Found bearer token in authorization header',\n })\n oauthToken = jwtFromHeader.replace('Bearer ', '')\n }\n }\n\n if (!oauthToken) {\n if (refreshToken && canSetHeaders) {\n debugLogger.info({\n msg: 'No access token found, but refresh token exists. Attempting to refresh...',\n refreshToken,\n })\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n } else {\n return {\n user: null,\n }\n }\n }\n\n let oauthTokenVerifyResult: Error | jwt.JwtPayload | null = null\n\n // First, try to verify token\n if (oauthToken) {\n oauthTokenVerifyResult = await this.jwtVerify({ payload, token: oauthToken })\n\n // If verify comes back null, there is no user\n if (oauthTokenVerifyResult === null) {\n return {\n user: null,\n }\n }\n\n // If verify comes back truthy, use it\n // but first set exp from refresh token\n // because access exp is likely very short lived\n if (\n typeof oauthTokenVerifyResult === 'object' &&\n !(oauthTokenVerifyResult instanceof Error)\n ) {\n if (refreshToken) {\n const refreshTokenExp = getTokenExp({ debugLogger, token: refreshToken })\n\n if (refreshTokenExp) {\n oauthTokenVerifyResult.exp = refreshTokenExp\n }\n }\n\n return this.verify({\n headers,\n payload,\n token: oauthTokenVerifyResult,\n })\n }\n }\n\n if (\n oauthTokenVerifyResult instanceof Error &&\n oauthTokenVerifyResult.name === 'TokenExpiredError' &&\n refreshToken &&\n !this.collectionOptions.usePayloadJWT &&\n canSetHeaders\n ) {\n const refreshed = await refreshTokens({ payload, refreshToken, strategy: this })\n\n debugLogger.info({\n msg: 'Token expired. Refreshing...',\n refreshed,\n refreshToken,\n })\n\n if (refreshed) {\n const verifyResult = await this.verify({\n headers,\n payload,\n token: refreshed.decodedOauthToken,\n })\n\n debugLogger.info({\n msg: 'Token refreshed. Verifying...',\n verifyResult,\n })\n\n if (verifyResult.responseHeaders) {\n mergeHeaders(verifyResult.responseHeaders, refreshed.headers)\n }\n\n return {\n responseHeaders: refreshed.headers,\n user: verifyResult.user,\n }\n } else {\n debugLogger.info({\n msg: 'Token refresh failed',\n refreshed,\n refreshToken,\n })\n }\n }\n\n return {\n user: null,\n }\n }\n\n async ensureMeta(): Promise<void> {\n if (this.metaPromise) {\n this.debugLog('strategy - metaPromise exists. Waiting for it to resolve...')\n await this.metaPromise\n }\n\n // If no meta or this.metaLastFetchedTime is more than 24 hours old, fetch meta\n if (!this.metaLastFetchedTime || Date.now() - this.metaLastFetchedTime.getTime() > 86_400_000) {\n this.debugLog(\n `Meta is stale. Fetching... Last fetched: ${this.metaLastFetchedTime || 'never'}`,\n )\n await this.fetchMeta()\n }\n }\n\n async fetchMeta(): Promise<void> {\n // If already in-flight, return the existing promise\n if (this.metaPromise) {\n this.debugLog('fetchMeta - returning existing metaPromise')\n return this.metaPromise\n }\n\n this.debugLog('fetchMeta - creating new metaPromise...')\n\n // Build the shared promise\n this.metaPromise = (async () => {\n let lastError: unknown\n\n for (let attempt = 1; attempt <= 5; attempt++) {\n try {\n this.meta = await fetch(this.identityMetadataURL).then((res) => res.json())\n this.debugLog(`fetchMeta - success on attempt ${attempt}`)\n\n if (this.meta?.jwks_uri) {\n this.jwks = await fetch(this.meta.jwks_uri).then((res) => res.json())\n }\n\n this.metaLastFetchedTime = new Date()\n this.debugLog(`fetchMeta - finished at ${this.metaLastFetchedTime.toISOString()}`)\n return\n } catch (error: unknown) {\n lastError = error\n this.debugLog(`fetchMeta - FAILED attempt ${attempt}/5: ${(error as Error)?.message}`)\n\n if (attempt < 5) {\n // Exponential backoff (up to 1s)\n await new Promise((resolve) => setTimeout(resolve, Math.min(attempt * 200, 1000)))\n }\n }\n }\n\n throw new APIError(\n `Failed to fetch identity metadata from \"${this.identityMetadataURL}\". Last error: ${\n (lastError as Error)?.message ?? 'unknown'\n }`,\n )\n })()\n\n try {\n await this.metaPromise\n } finally {\n this.metaPromise = undefined\n }\n }\n\n async generateOidcPEM(kid: string, alg: string): Promise<string> {\n const keys = this && this.jwks && Array.isArray(this.jwks.keys) ? this.jwks.keys : null\n\n let pubKey: null | string = null\n let foundKey = false\n\n if (!kid) {\n throw new Error('kid is missing')\n }\n\n if (!alg) {\n throw new Error('alg is missing')\n }\n\n if (!keys) {\n throw new Error('keys is missing')\n }\n\n for (const key of keys) {\n if (!('kid' in key) || key.kid !== kid) {\n continue\n }\n\n const cryptoKey = await jose.importJWK(key, alg)\n if (!(cryptoKey instanceof CryptoKey)) {\n throw new Error('importJWK did not return a CryptoKey')\n }\n\n pubKey = await jose.exportSPKI(cryptoKey)\n foundKey = true\n\n break\n }\n\n if (!foundKey) {\n throw new Error('a key with the specific kid cannot be found')\n }\n\n if (!pubKey) {\n throw new Error('generating public key pem failed')\n }\n\n return pubKey\n }\n\n async jwtVerify({ payload, token }: JwtVerifyArgs): Promise<Error | jwt.JwtPayload | null> {\n try {\n const verified = await validateProjectToken(token, getEnvironment())\n if (typeof verified !== 'string') {\n return verified\n }\n } catch (err: unknown) {\n payload.logger.error({\n err,\n msg: 'Error verifying jwt token',\n })\n\n if (err instanceof Error) {\n return err\n }\n return null\n }\n return null\n }\n}\n\ntype JwtVerifyArgs = {\n payload: Payload\n token: string\n}\n"],"names":["jose","APIError","parseCookies","validateProjectToken","getEnvironment","createDebugLogger","getTokenExp","mergeHeaders","refreshTokens","Strategy","clientID","clientSecret","collection","collectionOptions","cookieName","debug","debugLog","identityMetadataURL","jwks","meta","metaLastFetchedTime","metaPromise","metaPromiseResolve","name","pluginOptions","verify","options","identityMetadata","strategyName","args","console","log","ensureMeta","bind","authenticate","canSetHeaders","headers","payload","debugLogger","cookies","oauthToken","get","refreshToken","info","msg","disableJWTFromHeader","jwtFromHeader","startsWith","replace","refreshed","strategy","verifyResult","token","decodedOauthToken","responseHeaders","user","oauthTokenVerifyResult","jwtVerify","Error","refreshTokenExp","exp","usePayloadJWT","Date","now","getTime","fetchMeta","lastError","attempt","fetch","then","res","json","jwks_uri","toISOString","error","message","Promise","resolve","setTimeout","Math","min","undefined","generateOidcPEM","kid","alg","keys","Array","isArray","pubKey","foundKey","key","cryptoKey","importJWK","CryptoKey","exportSPKI","verified","err","logger"],"mappings":"AASA,YAAYA,UAAU,OAAM;AAC5B,SAASC,QAAQ,EAAEC,YAAY,QAAQ,UAAS;AAIhD,SAA6BC,oBAAoB,QAAQ,8BAA6B;AAEtF,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,iBAAiB,QAAQ,oCAAmC;AACrE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,QAAQ,+BAA8B;AAC3D,SAASC,aAAa,QAAQ,gCAA+B;AAe7D,OAAO,MAAMC;IACXC,SAAgB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MAAM;QAClB;QAEA,OAAO8B;IACT;IAEA,MAAM/B,UAAU,EAAEpB,OAAO,EAAEe,KAAK,EAAiB,EAA0C;QACzF,IAAI;YACF,MAAM2C,WAAW,MAAM5F,qBAAqBiD,OAAOhD;YACnD,IAAI,OAAO2F,aAAa,UAAU;gBAChC,OAAOA;YACT;QACF,EAAE,OAAOC,KAAc;YACrB3D,QAAQ4D,MAAM,CAACvB,KAAK,CAAC;gBACnBsB;gBACApD,KAAK;YACP;YAEA,IAAIoD,eAAetC,OAAO;gBACxB,OAAOsC;YACT;YACA,OAAO;QACT;QACA,OAAO;IACT;AACF"}
|
package/dist/oauth/types.d.ts
CHANGED
|
@@ -30,7 +30,7 @@ export interface CollectionOptions {
|
|
|
30
30
|
* Set to false to only accept the JWT from cookies
|
|
31
31
|
*/
|
|
32
32
|
disableJWTFromHeader?: boolean;
|
|
33
|
-
disableLocalStrategy?:
|
|
33
|
+
disableLocalStrategy?: boolean | IncomingAuthType['disableLocalStrategy'];
|
|
34
34
|
/**
|
|
35
35
|
* The logout button will either redirect to the IDP logout screen or
|
|
36
36
|
* automatically log the user out of the IDP depending on provider.
|
|
@@ -112,6 +112,11 @@ 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
|
+
*/
|
|
115
120
|
/**
|
|
116
121
|
* Accepts incoming request and allows for modification of cookie options
|
|
117
122
|
*/
|
|
@@ -120,11 +125,6 @@ export interface PluginOptions {
|
|
|
120
125
|
cookieOptions: CookieOptions;
|
|
121
126
|
headers: Headers;
|
|
122
127
|
}) => 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,GAAG,CAAC,UAAU,CAAA;CACtB,KAAK,OAAO,CAAC,kBAAkB,CAAC,CAAA;AAEjC,MAAM,MAAM,yBAAyB,GAAG;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,GAAG,IAAI,CAAA;AAER,MAAM,MAAM,mBAAmB,GAAG,CAAC,IAAI,EAAE;IACvC,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAK,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAA;AAEpE,MAAM,WAAW,iBAAiB;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAE/C,QAAQ,EAAE,MAAM,CAAA;IAChB,YAAY,CAAC,EAAE,MAAM,CAAA;IAErB;;;;OAIG;IAEH;;;;OAIG;IACH,oBAA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