@payloadcms/figma 0.0.1-alpha.42 → 0.0.1-alpha.6
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 +21 -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 +11 -15
- 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 +1 -2
- package/dist/auth/refresh.d.ts.map +1 -1
- package/dist/auth/refresh.js +12 -25
- package/dist/auth/refresh.js.map +1 -1
- package/dist/auth/token-store.d.ts +0 -12
- package/dist/auth/token-store.d.ts.map +1 -1
- package/dist/auth/token-store.js +5 -28
- package/dist/auth/token-store.js.map +1 -1
- package/dist/auth/types.d.ts +4 -7
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -39
- 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 -72
- 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 -105
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/list-tokens.d.ts +3 -3
- package/dist/commands/list-tokens.d.ts.map +1 -1
- package/dist/commands/list-tokens.js +7 -22
- 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 +12 -30
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/logout.d.ts +4 -5
- package/dist/commands/logout.d.ts.map +1 -1
- package/dist/commands/logout.js +13 -56
- 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/exports/client.d.ts +0 -1
- package/dist/exports/client.d.ts.map +1 -1
- package/dist/exports/client.js +0 -1
- package/dist/exports/client.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 +4 -5
- 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 +11 -21
- package/dist/oauth/endpoints/getLoginEndpoint.js.map +1 -1
- package/dist/oauth/endpoints/getLogoutEndpoint.d.ts.map +1 -1
- package/dist/oauth/endpoints/getLogoutEndpoint.js +4 -7
- package/dist/oauth/endpoints/getLogoutEndpoint.js.map +1 -1
- package/dist/oauth/index.d.ts.map +1 -1
- package/dist/oauth/index.js +13 -40
- 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/getAdminPath.d.ts +8 -0
- package/dist/oauth/utilities/getAdminPath.d.ts.map +1 -0
- package/dist/oauth/utilities/getAdminPath.js +9 -0
- package/dist/oauth/utilities/getAdminPath.js.map +1 -0
- package/dist/oauth/utilities/refreshTokens.d.ts.map +1 -1
- package/dist/oauth/utilities/refreshTokens.js +1 -1
- package/dist/oauth/utilities/refreshTokens.js.map +1 -1
- package/dist/plugin/build-config.d.ts +4 -21
- package/dist/plugin/build-config.d.ts.map +1 -1
- package/dist/plugin/build-config.js +7 -113
- 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 +32 -38
- package/dist/utils/lambda-config.js.map +1 -1
- package/dist/utils/messages.js +8 -8
- 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 +9 -27
- 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 -3914
- 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 -586
- package/dist/db-content-api/index.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 -34
- 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/buildPathTypes.d.ts +0 -12
- package/dist/db-content-api/utilities/buildPathTypes.d.ts.map +0 -1
- package/dist/db-content-api/utilities/buildPathTypes.js +0 -157
- package/dist/db-content-api/utilities/buildPathTypes.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 -32
- package/dist/db-content-api/utilities/data/index.d.ts.map +0 -1
- package/dist/db-content-api/utilities/data/index.js +0 -190
- 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 -121
- 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/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 -168
- 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 -32
- 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 -8
- 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 -17
- 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 -144
- 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 -56
- 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
- package/dist/utils/format-env-suffix.d.ts +0 -12
- package/dist/utils/format-env-suffix.d.ts.map +0 -1
- package/dist/utils/format-env-suffix.js +0 -13
- package/dist/utils/format-env-suffix.js.map +0 -1
- package/dist/utils/version-check.d.ts +0 -3
- package/dist/utils/version-check.d.ts.map +0 -1
- package/dist/utils/version-check.js +0 -38
- package/dist/utils/version-check.js.map +0 -1
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';
|
|
@@ -85,46 +84,23 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
85
84
|
if (collectionOptions.usePayloadJWT) {
|
|
86
85
|
cookieName = `${config.cookiePrefix || 'payload'}-token`;
|
|
87
86
|
}
|
|
87
|
+
const usernameField = getUsernameField({
|
|
88
|
+
collection: existingCollection,
|
|
89
|
+
collectionOptions
|
|
90
|
+
});
|
|
88
91
|
// Check if email field exists, if not add it
|
|
89
92
|
const hasEmailField = existingCollection.fields.some((field)=>'name' in field && field.name === 'email');
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
93
|
+
const fields = [
|
|
94
|
+
...existingCollection.fields,
|
|
95
|
+
...typeof adminCollectionOptions.usernameField === 'string' ? [] : [
|
|
96
|
+
usernameField
|
|
97
|
+
],
|
|
98
|
+
...!hasEmailField ? [
|
|
96
99
|
{
|
|
97
100
|
name: 'email',
|
|
98
|
-
type: 'email'
|
|
99
|
-
admin: {
|
|
100
|
-
description: 'Managed by Figma',
|
|
101
|
-
readOnly: true
|
|
102
|
-
},
|
|
103
|
-
unique: true
|
|
101
|
+
type: 'email'
|
|
104
102
|
}
|
|
105
|
-
]
|
|
106
|
-
};
|
|
107
|
-
const usernameField = getUsernameField({
|
|
108
|
-
collection: collectionWithEmail,
|
|
109
|
-
collectionOptions
|
|
110
|
-
});
|
|
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
|
-
const fields = [
|
|
124
|
-
...collectionWithEmail.fields.map((field)=>fieldAffectsData(field) && field.name === usernameField.name ? readOnlyUsernameField : field),
|
|
125
|
-
...isUsernameFieldString ? [] : [
|
|
126
|
-
readOnlyUsernameField
|
|
127
|
-
]
|
|
103
|
+
] : []
|
|
128
104
|
];
|
|
129
105
|
if (disabled) {
|
|
130
106
|
return {
|
|
@@ -134,6 +110,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
134
110
|
}
|
|
135
111
|
const strategy = new Strategy({
|
|
136
112
|
clientID: collectionOptions.clientID,
|
|
113
|
+
clientSecret: collectionOptions.clientSecret,
|
|
137
114
|
collection: existingCollection,
|
|
138
115
|
collectionOptions,
|
|
139
116
|
cookieName,
|
|
@@ -165,10 +142,6 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
|
|
|
165
142
|
}
|
|
166
143
|
return {
|
|
167
144
|
...existingCollection,
|
|
168
|
-
access: {
|
|
169
|
-
...existingCollection.access || {},
|
|
170
|
-
create: ()=>false
|
|
171
|
-
},
|
|
172
145
|
auth: {
|
|
173
146
|
...typeof existingCollection.auth === 'object' ? existingCollection.auth : {},
|
|
174
147
|
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;gBACF;gBACAQ,MAAMN,uBAAuBI,WAAW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lB;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/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 const usernameField = getUsernameField({\n collection: existingCollection,\n collectionOptions,\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 const fields = [\n ...existingCollection.fields,\n ...(typeof adminCollectionOptions.usernameField === 'string' ? [] : [usernameField]),\n ...(!hasEmailField\n ? [\n {\n name: 'email',\n type: 'email' as const,\n },\n ]\n : []),\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","hasEmailField","fields","some","field","name","type","strategy","clientID","clientSecret","identityMetadata","verify","authStrategy","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,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C3B,EAAE;4BACN,mEAAmE;+BAC/D,CAAC3B,kBAAkBE,aAAa,GAAG;gCAAClC,UAAU;oCAAEiC;gCAAW;6BAAG,GAAG,EAAE;yBACxE;wBACD2B,SAAS;+BACH,OAAO7B,mBAAmB0B,KAAK,KAAK,YACxC7B,MAAMC,OAAO,CAACE,mBAAmB0B,KAAK,CAACG,OAAO,IAC1C7B,mBAAmB0B,KAAK,CAACG,OAAO,GAChC,EAAE;4BACN3D,eAAe;gCAAEK;gCAAesC;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/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1B,CAAA;IACD,mBAAmB,CAAC,EAAE,IAAI,CAAA;IAE1B,WAAW,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IAC3B,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAA;IAC/B,IAAI,EAAE,MAAM,CAAA;IACZ,aAAa,EAAE,aAAa,CAAA;IAC5B,MAAM,EAAE,cAAc,CAAA;gBAEV,OAAO,EAAE,OAAO;IAiBtB,YAAY,CAAC,EACjB,aAAa,EACb,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,IA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AClB;QAEA,OAAOgC;IACT;IAEA,MAAMjC,UAAU,EAAEpB,OAAO,EAAEe,KAAK,EAAiB,EAA0C;QACzF,IAAI;YACF,MAAM6C,WAAW,MAAM7F,qBAAqBgD,OAAO/C;YACnD,IAAI,OAAO4F,aAAa,UAAU;gBAChC,OAAOA;YACT;QACF,EAAE,OAAOC,KAAc;YACrB7D,QAAQ8D,MAAM,CAACvB,KAAK,CAAC;gBACnBsB;gBACAtD,KAAK;YACP;YAEA,IAAIsD,eAAexC,OAAO;gBACxB,OAAOwC;YACT;YACA,OAAO;QACT;QACA,OAAO;IACT;AACF"}
|
|
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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Q,YAAY,MAAM3F,KAAK4F,SAAS,CAACF,KAAKN;YAC5C,IAAI,CAAEO,CAAAA,qBAAqBE,SAAQ,GAAI;gBACrC,MAAM,IAAInC,MAAM;YAClB;YAEA8B,SAAS,MAAMxF,KAAK8F,UAAU,CAACH;YAC/BF,WAAW;YAEX;QACF;QAEA,IAAI,CAACA,UAAU;YACb,MAAM,IAAI/B,MAAM;QAClB;QAEA,IAAI,CAAC8B,QAAQ;YACX,MAAM,IAAI9B,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,C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CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,KAAK,EAAE,KAAK,CAAA;IACZ,IAAI,EAAE,KAAK,CAAA;CACZ,CAAA"}
|
package/dist/oauth/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/oauth/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type jwt from 'jsonwebtoken'\nimport type {\n AuthStrategyResult,\n CollectionConfig,\n CustomComponent,\n EmailField,\n IncomingAuthType,\n Payload,\n PayloadRequest,\n TextField,\n} from 'payload'\n\nexport type Done = (error: any, user?: any, info?: unknown) => void\n\nexport type VerifyFunction = (args: {\n headers: Headers\n payload: Payload\n token: jwt.JwtPayload\n}) => Promise<AuthStrategyResult>\n\nexport type AfterOAuthLoginHookResult = {\n redirect?: string\n} | void\n\nexport type AfterOAuthLoginHook = (args: {\n access_token?: string\n id_token?: string\n refresh_token?: string\n req: PayloadRequest\n}) => AfterOAuthLoginHookResult | Promise<AfterOAuthLoginHookResult>\n\nexport interface CollectionOptions {\n authorizationURLParams?: Record<string, string>\n\n clientID: string\n clientSecret?: string\n\n /**\n * Whether to disable the local strategy for this collection.\n *\n * @default true\n */\n\n /**\n * By default, accept a JWT from the authorization header\n *\n * Set to false to only accept the JWT from cookies\n */\n disableJWTFromHeader?: boolean\n\n disableLocalStrategy?:
|
|
1
|
+
{"version":3,"sources":["../../src/oauth/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type jwt from 'jsonwebtoken'\nimport type {\n AuthStrategyResult,\n CollectionConfig,\n CustomComponent,\n EmailField,\n IncomingAuthType,\n Payload,\n PayloadRequest,\n TextField,\n} from 'payload'\n\nexport type Done = (error: any, user?: any, info?: unknown) => void\n\nexport type VerifyFunction = (args: {\n headers: Headers\n payload: Payload\n token: jwt.JwtPayload\n}) => Promise<AuthStrategyResult>\n\nexport type AfterOAuthLoginHookResult = {\n redirect?: string\n} | void\n\nexport type AfterOAuthLoginHook = (args: {\n access_token?: string\n id_token?: string\n refresh_token?: string\n req: PayloadRequest\n}) => AfterOAuthLoginHookResult | Promise<AfterOAuthLoginHookResult>\n\nexport interface CollectionOptions {\n authorizationURLParams?: Record<string, string>\n\n clientID: string\n clientSecret?: string\n\n /**\n * Whether to disable the local strategy for this collection.\n *\n * @default true\n */\n\n /**\n * By default, accept a JWT from the authorization header\n *\n * Set to false to only accept the JWT from cookies\n */\n disableJWTFromHeader?: boolean\n\n disableLocalStrategy?: boolean | IncomingAuthType['disableLocalStrategy']\n /**\n * The logout button will either redirect to the IDP logout screen or\n * automatically log the user out of the IDP depending on provider.\n *\n * @default false\n */\n endOAuthSessionOnLogout?: boolean\n hooks?: {\n afterLogin?: AfterOAuthLoginHook[]\n }\n /**\n * The OpenID metadata endpoint for the identity provider.\n *\n * @example http://localhost:8080/realms/master/.well-known/openid-configuration\n * @example https://myapp.auth0.com/.well-known/openid-configuration\n */\n identityMetadata: string\n /**\n * Custom React component to use as the login button on the login page.\n */\n LoginButton?: CustomComponent | false\n /**\n * The OAuth2.0 scope to request from the identity provider.\n *\n * @default ['openid', 'profile', 'email']\n */\n scope?: string[]\n /**\n * The Payload collection slug to apply the OAuth2.0 strategy to.\n */\n slug: string\n /**\n * Property to use as the token to decode from the OAuth2.0 response.\n *\n * This is passed to the default or custom `verify` function.\n *\n * @default 'access_token'\n */\n token?: 'access_token' | 'id_token'\n\n /**\n * Have Payload maintain the JWT cookie.\n *\n * This is for when the IDP does not support silently refreshing tokens in the background.\n */\n usePayloadJWT?: boolean\n\n /**\n * The Payload field to use as the username field for the user\n * When a text is used, the plugin will find the collection field with the name provided\n * Alternatively define the entire field to use\n * @default\n *\n * ```ts\n * {\n * type: 'text',\n * name: 'preferredUsername',\n * unique: true,\n * admin: {\n * position: 'sidebar',\n * readOnly: true,\n * },\n * }\n * ```\n */\n usernameField?: EmailField | string | TextField\n\n /**\n * Custom verify function that receives the token and performs any logic.\n * By default, the defaultVerify function is used.\n */\n verify?: VerifyFunction\n}\n\nexport interface PluginOptions {\n /**\n * The collections to apply the OAuth2.0 strategy to.\n */\n collections: CollectionOptions[]\n /**\n * The name of the cookie to use for storing the user's token.\n *\n * @default 'payload-oauth-token'\n */\n cookieName?: string\n /**\n * Debug mode will log additional information to the console.\n *\n * NOTE: This will log sensitive information to the console.\n */\n\n /**\n * Accepts incoming request and allows for modification of cookie options\n */\n createCookieOptions?: (args: {\n collection: CollectionConfig\n cookieOptions: CookieOptions\n headers: Headers\n }) => CookieOptions\n\n debug?: boolean\n /**\n * Disables the plugin functionality while leaving in types, fields and component modifications.\n * @default false\n */\n disabled?: boolean\n /**\n * OAuth2.0 requires a URL to redirect the user to.\n * If you do not have a `config.serverURL` defined in your Payload config, you must define this string to be set as where the identity provider should redirect users once logged in.\n */\n redirectServerURL?: string\n /**\n * Override the strategy name used for this plugin.\n *\n * This should only be overridden to accomodate multiple plugin\n * invocations against a single user collection.\n *\n * If you have a custom basePath defined in your Next config,\n * this value should not contain that path.\n *\n * @default 'oauth'\n */\n strategyName?: string\n}\n\nexport type CookieOptions = {\n domain?: string\n expires?: Date | number\n httpOnly?: boolean\n maxAge?: number\n path?: string\n sameSite?: 'Lax' | 'None' | 'Strict'\n secure?: boolean\n}\n\nexport type StateObj = {\n /**\n * Redirect to use if the login fails\n */\n failedRedirect?: string\n /**\n * Redirect to use after the login is successful\n */\n redirect?: string\n /**\n * The URL that will be used for Payload to redirect to\n */\n serverURL?: string\n /**\n * Encrypted signature to be verified\n */\n sig: string\n /**\n * Code verifier used for PKCE\n */\n verifier: string\n}\n\nexport type LogFn = {\n (msg: string, ...args: any[]): void\n (obj: unknown, msg?: string, ...args: any[]): void\n <T extends object>(obj: T, msg?: string, ...args: any[]): void\n}\n\nexport type DebugLogger = {\n error: LogFn\n info: LogFn\n}\n"],"names":[],"mappings":"AAAA,qDAAqD,GAwNrD,WAGC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCookieOptions.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,
|
|
1
|
+
{"version":3,"file":"createCookieOptions.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,SAAS,CAAA;AAE/D,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAE/D,UAAU,IAAI;IACZ,UAAU,EAAE,gBAAgB,CAAA;IAC5B,OAAO,EAAE,OAAO,CAAA;IAChB,aAAa,EAAE,aAAa,CAAA;CAC7B;AAED,eAAO,MAAM,mBAAmB,4CAI7B,IAAI,KAAG,aA8CT,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { CookieOptions, PluginOptions } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n headers: Headers\n pluginOptions: PluginOptions\n}\n\nexport const createCookieOptions = ({\n collection,\n headers,\n pluginOptions,\n}: Args): CookieOptions => {\n let cookieOptions: CookieOptions = {\n domain: undefined,\n httpOnly: true,\n path: '/',\n sameSite: undefined,\n secure: false,\n }\n\n if (typeof collection.auth === 'object' && typeof collection.auth.cookies === 'object') {\n const { domain, sameSite, secure } = collection.auth.cookies\n if (typeof secure === 'boolean') {\n cookieOptions.secure = secure\n }\n if (typeof sameSite === 'string') {\n cookieOptions.sameSite = sameSite as 'Lax'\n }\n if (typeof domain === 'string') {\n cookieOptions.domain = domain\n }\n }\n\n if (typeof collection.auth === 'object' && typeof collection.auth.cookies === 'object') {\n if (collection.auth.cookies.secure) {\n cookieOptions.secure = true\n }\n if (collection.auth.cookies.sameSite) {\n cookieOptions.sameSite =\n typeof collection.auth.cookies.sameSite === 'string'\n ? collection.auth.cookies.sameSite\n : 'Lax'\n }\n if (collection.auth.cookies.domain) {\n cookieOptions.domain = collection.auth.cookies.domain\n }\n }\n\n if (typeof pluginOptions.createCookieOptions === 'function') {\n cookieOptions = pluginOptions.createCookieOptions({\n collection,\n cookieOptions,\n headers,\n })\n }\n\n return cookieOptions\n}\n"],"names":["createCookieOptions","collection","headers","pluginOptions","cookieOptions","domain","undefined","httpOnly","path","sameSite","secure","auth","cookies"],"mappings":"AAUA,OAAO,MAAMA,sBAAsB,CAAC,EAClCC,UAAU,EACVC,OAAO,EACPC,aAAa,EACR;IACL,IAAIC,gBAA+B;QACjCC,QAAQC;QACRC,UAAU;QACVC,MAAM;QACNC,UAAUH;QACVI,QAAQ;IACV;IAEA,IAAI,OAAOT,WAAWU,IAAI,KAAK,YAAY,OAAOV,WAAWU,IAAI,CAACC,OAAO,KAAK,UAAU;QACtF,MAAM,EAAEP,MAAM,EAAEI,QAAQ,EAAEC,MAAM,EAAE,GAAGT,WAAWU,IAAI,CAACC,OAAO;QAC5D,IAAI,OAAOF,WAAW,WAAW;YAC/BN,cAAcM,MAAM,GAAGA;QACzB;QACA,IAAI,OAAOD,aAAa,UAAU;YAChCL,cAAcK,QAAQ,GAAGA;QAC3B;QACA,IAAI,OAAOJ,WAAW,UAAU;YAC9BD,cAAcC,MAAM,GAAGA;QACzB;IACF;IAEA,IAAI,OAAOJ,WAAWU,IAAI,KAAK,YAAY,OAAOV,WAAWU,IAAI,CAACC,OAAO,KAAK,UAAU;QACtF,IAAIX,WAAWU,IAAI,CAACC,OAAO,CAACF,MAAM,EAAE;YAClCN,cAAcM,MAAM,GAAG;QACzB;QACA,IAAIT,WAAWU,IAAI,CAACC,OAAO,CAACH,QAAQ,EAAE;YACpCL,cAAcK,QAAQ,GACpB,OAAOR,WAAWU,IAAI,CAACC,OAAO,CAACH,QAAQ,KAAK,WACxCR,WAAWU,IAAI,CAACC,OAAO,CAACH,QAAQ,GAChC;QACR;QACA,IAAIR,WAAWU,IAAI,CAACC,OAAO,CAACP,MAAM,EAAE;YAClCD,cAAcC,MAAM,GAAGJ,WAAWU,IAAI,CAACC,OAAO,CAACP,MAAM;QACvD;IACF;IAEA,IAAI,OAAOF,cAAcH,mBAAmB,KAAK,YAAY;QAC3DI,gBAAgBD,cAAcH,mBAAmB,CAAC;YAChDC;YACAG;YACAF;QACF;IACF;IAEA,OAAOE;AACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/utilities/createCookieOptions.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\n\nimport type { CookieOptions, PluginOptions } from '../types.js'\n\ninterface Args {\n collection: CollectionConfig\n headers: Headers\n pluginOptions: PluginOptions\n}\n\nexport const createCookieOptions = ({\n collection,\n headers,\n pluginOptions,\n}: Args): CookieOptions => {\n let cookieOptions: CookieOptions = {\n domain: undefined,\n httpOnly: true,\n path: '/',\n sameSite: undefined,\n secure: false,\n }\n\n if (typeof collection.auth === 'object' && typeof collection.auth.cookies === 'object') {\n const { domain, sameSite, secure } = collection.auth.cookies\n if (typeof secure === 'boolean') {\n cookieOptions.secure = secure\n }\n if (typeof sameSite === 'string') {\n cookieOptions.sameSite = sameSite as 'Lax'\n }\n if (typeof domain === 'string') {\n cookieOptions.domain = domain\n }\n }\n\n if (typeof collection.auth === 'object' && typeof collection.auth.cookies === 'object') {\n if (collection.auth.cookies.secure) {\n cookieOptions.secure = true\n }\n if (collection.auth.cookies.sameSite) {\n cookieOptions.sameSite =\n typeof collection.auth.cookies.sameSite === 'string'\n ? collection.auth.cookies.sameSite\n : 'Lax'\n }\n if (collection.auth.cookies.domain) {\n cookieOptions.domain = collection.auth.cookies.domain\n }\n }\n\n if (typeof pluginOptions.createCookieOptions === 'function') {\n cookieOptions = pluginOptions.createCookieOptions({\n collection,\n cookieOptions,\n headers,\n })\n }\n\n return cookieOptions\n}\n"],"names":["createCookieOptions","collection","headers","pluginOptions","cookieOptions","domain","undefined","httpOnly","path","sameSite","secure","auth","cookies"],"mappings":"A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+
import type { ClientConfig, SanitizedConfig } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* This is the path to the admin panel WITHOUT domain.
|
|
4
|
+
*
|
|
5
|
+
* This respects the `basePath` property in the Next config.
|
|
6
|
+
*/
|
|
7
|
+
export declare const getAdminPath: (config: ClientConfig | SanitizedConfig) => string;
|
|
8
|
+
//# sourceMappingURL=getAdminPath.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getAdminPath.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/getAdminPath.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAE5D;;;;GAIG;AACH,eAAO,MAAM,YAAY,WAAY,YAAY,GAAG,eAAe,WAElE,CAAA"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This is the path to the admin panel WITHOUT domain.
|
|
3
|
+
*
|
|
4
|
+
* This respects the `basePath` property in the Next config.
|
|
5
|
+
*/ export const getAdminPath = (config)=>{
|
|
6
|
+
return `${process.env.NEXT_BASE_PATH ?? ''}${config.routes?.admin || '/admin'}`;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=getAdminPath.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/utilities/getAdminPath.ts"],"sourcesContent":["import type { ClientConfig, SanitizedConfig } from 'payload'\n\n/**\n * This is the path to the admin panel WITHOUT domain.\n *\n * This respects the `basePath` property in the Next config.\n */\nexport const getAdminPath = (config: ClientConfig | SanitizedConfig) => {\n return `${process.env.NEXT_BASE_PATH ?? ''}${config.routes?.admin || '/admin'}`\n}\n"],"names":["getAdminPath","config","process","env","NEXT_BASE_PATH","routes","admin"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,eAAe,CAACC;IAC3B,OAAO,GAAGC,QAAQC,GAAG,CAACC,cAAc,IAAI,KAAKH,OAAOI,MAAM,EAAEC,SAAS,UAAU;AACjF,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refreshTokens.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/refreshTokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAItC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;
|
|
1
|
+
{"version":3,"file":"refreshTokens.d.ts","sourceRoot":"","sources":["../../../src/oauth/utilities/refreshTokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAItC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAUpD,UAAU,IAAI;IACZ,OAAO,EAAE,OAAO,CAAA;IAChB,YAAY,EAAE,MAAM,CAAA;IACpB,QAAQ,EAAE,QAAQ,CAAA;CACnB;AAED,KAAK,MAAM,GACP;IACE,iBAAiB,EAAE,GAAG,CAAC,UAAU,CAAA;IACjC,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;CACd,GACD,KAAK,CAAA;AAET,eAAO,MAAM,aAAa,wCAA+C,IAAI,KAAG,OAAO,CAAC,MAAM,CAmE7F,CAAA"}
|
|
@@ -16,7 +16,7 @@ export const refreshTokens = async ({ payload, refreshToken, strategy })=>{
|
|
|
16
16
|
// so we will refresh both tokens
|
|
17
17
|
try {
|
|
18
18
|
// Get another project token
|
|
19
|
-
const { expiresAt, token } = await getProjectToken(refreshToken,
|
|
19
|
+
const { expiresAt, token } = await getProjectToken(refreshToken, 'someproject');
|
|
20
20
|
debugLogger.info({
|
|
21
21
|
expiresAt,
|
|
22
22
|
msg: 'Received new tokens from Figma API',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/oauth/utilities/refreshTokens.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\nimport type { Payload } from 'payload'\n\nimport { generateCookie } from 'payload'\n\nimport type { Strategy } from '../strategy/index.js'\n\nimport { getProjectToken } from '../../api/figma-api.js'\nimport { validateProjectToken } from '../../auth/jwt-validator.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createCookieOptions } from './createCookieOptions.js'\nimport { createDebugLogger } from './createDebugLogger.js'\nimport { getCookieExpiration } from './getCookieExpiration.js'\n\ninterface Args {\n payload: Payload\n refreshToken: string\n strategy: Strategy\n}\n\ntype Result =\n | {\n decodedOauthToken: jwt.JwtPayload\n headers: Headers\n token: string\n }\n | false\n\nexport const refreshTokens = async ({ payload, refreshToken, strategy }: Args): Promise<Result> => {\n const debugLogger = createDebugLogger(payload, strategy.debug)\n\n debugLogger.info({\n msg: 'Refreshing tokens',\n })\n\n const headers = new Headers()\n\n // At this point, access token is expired\n // but refresh token is still valid\n // so we will refresh both tokens\n\n try {\n // Get another project token\n const { expiresAt, token } = await getProjectToken(
|
|
1
|
+
{"version":3,"sources":["../../../src/oauth/utilities/refreshTokens.ts"],"sourcesContent":["import type jwt from 'jsonwebtoken'\nimport type { Payload } from 'payload'\n\nimport { generateCookie } from 'payload'\n\nimport type { Strategy } from '../strategy/index.js'\n\nimport { getProjectToken } from '../../api/figma-api.js'\nimport { validateProjectToken } from '../../auth/jwt-validator.js'\nimport { getEnvironment } from '../../constants.js'\nimport { createCookieOptions } from './createCookieOptions.js'\nimport { createDebugLogger } from './createDebugLogger.js'\nimport { getCookieExpiration } from './getCookieExpiration.js'\nimport { getTokenExp } from './getTokenExp.js'\n\ninterface Args {\n payload: Payload\n refreshToken: string\n strategy: Strategy\n}\n\ntype Result =\n | {\n decodedOauthToken: jwt.JwtPayload\n headers: Headers\n token: string\n }\n | false\n\nexport const refreshTokens = async ({ payload, refreshToken, strategy }: Args): Promise<Result> => {\n const debugLogger = createDebugLogger(payload, strategy.debug)\n\n debugLogger.info({\n msg: 'Refreshing tokens',\n })\n\n const headers = new Headers()\n\n // At this point, access token is expired\n // but refresh token is still valid\n // so we will refresh both tokens\n\n try {\n // Get another project token\n const { expiresAt, token } = await getProjectToken(refreshToken, 'someproject')\n\n debugLogger.info({\n expiresAt,\n msg: 'Received new tokens from Figma API',\n token,\n })\n\n // On error, no user\n if (!token) {\n debugLogger.error({\n msg: 'Error refreshing tokens',\n })\n return false\n }\n\n if (token) {\n debugLogger.info({\n msg: 'Successfully refreshed project token',\n token,\n })\n\n const expires_in = new Date(expiresAt)\n\n const cookieOptions = createCookieOptions({\n collection: strategy.collection,\n headers,\n pluginOptions: strategy.pluginOptions,\n })\n\n const tokenCookie = generateCookie({\n ...cookieOptions,\n name: strategy.cookieName,\n expires: getCookieExpiration(expires_in),\n returnCookieAsObject: false,\n value: token,\n }) as string\n\n headers.append('Set-Cookie', tokenCookie)\n\n const decodedOauthToken = await validateProjectToken(token, getEnvironment())\n\n return { decodedOauthToken, headers, token }\n }\n } catch (error) {\n debugLogger.error({\n err: error,\n msg: 'Error refreshing tokens',\n })\n }\n\n return false\n}\n"],"names":["generateCookie","getProjectToken","validateProjectToken","getEnvironment","createCookieOptions","createDebugLogger","getCookieExpiration","refreshTokens","payload","refreshToken","strategy","debugLogger","debug","info","msg","headers","Headers","expiresAt","token","error","expires_in","Date","cookieOptions","collection","pluginOptions","tokenCookie","name","cookieName","expires","returnCookieAsObject","value","append","decodedOauthToken","err"],"mappings":"AAGA,SAASA,cAAc,QAAQ,UAAS;AAIxC,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,mBAAmB,QAAQ,2BAA0B;AAiB9D,OAAO,MAAMC,gBAAgB,OAAO,E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